I need to create a db structure where "Supplier" inherits from "Client". I used to have an association on Client that I want to move to Supplier, but I can figure out how to define this. IN VS When I add an association to Supplier I can only associate the fields explicitly defined in Supplier (And I need to associate Client.Id).
Can I use the workaround where I add ClientId in Supplier?
(updated)
Right; I see what you mean. I suspect that with LINQ-to-SQL you can only associate to the base-class, and it will give you the appropriate types. You can filter with OfType<T> etc.
You can't simply add the id to the derived class, as it needs to be resolvable by LINQ when examining query expressions - and a bespoke standalone property won't be.
However, I also recall that this is possible in EF (even if I don't like EF overly ;-p).
Related
We need to add a new functionality in our app, such that for SELECT queries performed by our DbContext on its DbSets, for example when calling MyDbContext.Users, or MyDbContext.Students etc (User and Student inherit from a BaseEntity class, which includes a propery IsActive), we will be able to intercept them, check if the entity is of this base type BaseEntity, and modify the queries in some way, for example add a where clause to check if IsActive is true. I've tried to look into the IDbCommandInterceptor interface but its methods, including the one that is probably relevent to me, ReaderExecuting, intercept all kinds of SELECT statements performed on the database, not just the ones for the MyDbContext's dbsets.
How can I do this in the correct way?
Thanks, ashilon
Interceptors, in this instance, are probably not what you want. They intercept all queries for all DbContexts and you can only modify the SQL directly. This is too dangerous when you want to add a where clause because joins could mess everything up.
If you have a repository or some base class all queries go through, do it there. If you are always doing context.Students.Where(...) then there is a sneaky thing you can do, but not entirely sure if this'll work but I don't see why it wouldn't.
On your DbContext class, I would change all the DbSet property namesd, like Students, to StudentsDbSet. I would then add this property to replace it:
public IQueryable<Student> Students
{
get { return StudentdsDbSet.Where(a => a.IsActive); }
}
All old code would now refer to this property that forces IsActive only records. Then if you needed non-active students, you could do StudentsDbSet.Where(...) and you'd be good to go.
When creating a View based on a PIVOT query all the view fields become NULLABLE in the view metadata, is there any way to make them NOT NULLABLE?
I'm using the NVL function in the pivoted fields I need to be NOT NULL but they still become NULLABLE.
This is a problem to me because I'm using MS Entity Framework and it won't update the model based on tables or views without NOT NULLABLE columns.
#Miguel, I don't know the "MS Entity Framework" but the name makes it sound like a framework that is oriented towards editing data. 'Entity' is typically used for structuring a cache of database data in preparation for changing and updating that data back into the database. This does not seem like what you want to do.
Re-reading this question I believe that you have some sort of pivot generator you are using to create the view on-the-fly for the user. For this reason you do not intend to revise the Entity Model. I don't think you need an entity model at all.
An Entity Framework is likely to be looking for NOT NULL columns in order to find a 'primary key' or other row-level identifier that it can use. Why does it want these?
provide a key usable to update any row
provide key for paginating the result set
provide a key to support in-memory filtering of the result set
support dynamic sorting operations on the result set
I also surmise you have some sort of UI control that presents 'Entity' collections very nicely and so you want to use that control.
The control may not need an 'Entity' - check to see what its interface is. Perhaps there is a superclass of Entity or an interface that you can generate rather than an updateable Entity. If you can do that, you should be able to present it in the spiffy UI control and not hit the wall with your NULLABLE columns.
One of possible solutions is generating a new table on the fly based on results of query and tuning constraints for this table after that.
I don't like this method for too many dynamic SQL :)
Another solution is a prebuilt materialized view.
Look here (Oracle docs) for "ON PREBUILT TABLE Clause".
You need to update your model in Visual Studio (VS). Because this doesn't know what type information is in every column. Then you have to specify in the query of pivot table the data type. For example, Use to_number for specify a explicit conversion. When you going to update the model in VS you must based in for example materialized view (with explicitly defined data types). Please create Materialized view with explicitly defined data types based in the pivot table (this have to contain not only nvl function else defined data types, string, number, etc ) and then Update your model.
Only Materialized view? No, it can be a table (but is troublesome). Can be It direct of the pivot table? Does not always work (as in your case). Important Is to have defined data types.
You could use code-first if you don't have to many of these views, Scott Gu has a good article "Code first with existing database" that shows how to do this.
This might entail having 2 ways to access the db, which may or may not work for you.
I have an EmployeeDTO that respresents an Employee record in the database. The Employee table has a relationship to a Department and a 1-to-many relationship to Permission.
In my entities, these are represented as a fully expanded Department property and a List of fully expanded permission objects.
The question is should the DTO have a fully expanded DepartmentDTO property of a DepartmentId? Should the DTO have a list of fully expanded PermissionDTO properties of List of PermissionId?
Just like everything in design, it depends on your needs.
If you need to frequently see and
bind to child properties and you want
to make it as easy as possible for
developers to use your DTOs, you may
want explicit factory methods to give
you fully expanded child properties.
If you want simplicity of code, don't
expand the foreign key properties and
just let developers get the child
object/collections they want by key
as needed.
You may run into problems in recursion; do you also expand all the foreign-key properties of the Department object too? What if there is a reference to another EmployeeDTO in a subclass of Department?
Microsoft's Entity Framework, as well as other popular business object frameworks, handle this concept by lazy loading -- only fetch the full expanded child property if it is called for by the code. This is probably the most flexible solution, but has a little overhead/lag as child properties can't be fetched in the same database call as the parent object. These are of course not purely DTOs.
Yes and No. It depends on the call and if you would need all extra properties in every call. It can also depends on the ORM technology you use which can implement lazy loading and can affect your decision (if you are passing straight entity objects although it is not recommended).
It is common to create one case DTO containing all necessary properties and one or more DTO object that expose more functionality and are used it other methods. For example, I have a BasicUser class which only contains UserName and DisplayName and I have User which contains more including Permissions and inherits from `BasicUser.
I'm using Linq-To-Sql and inside my DBML there are objects built from the database connection provided.
If you click on an association line between two tables and view the properties on it, you will get the following:
Cardinality
Child Property
Access
Inheritance Modifier
Name
Parent Property
Access
Inheritance Modifier
Name
Participating Properties
Unique
My question is, where does Linq-To-Sql get the "Name" properties from? Where is the correlation to the actual database?
I ask this because if this table happens to be a parent to several children, Linq-To-Sql will just simply name these properties, "SomeParentName", "SomeParentName2", "SomeParentName3" , etc. So you'd have to go into the DBML and manually change these names to something meaningful every time you update this table.
Any help you can provide would be appreciated.
Part 2 of my question might be how do you guys handle these situations?
As for the Name: It takes the child / parent and comes up with something based on some internal voodoo. Don't ask me how.
As for Part 2: If you tend to have to redo stuff every time you update something I STRONGLY suggest switching to Entity Framework. It's very similar, but you can just hit "update" and your modifications are kept.
I'm reading about the Entity Framework 4.0 and I was wondering why should I create a complex type and not a new Entity (Table) and a relation between them?
The perfect example is an address. Using a complex type for an address is much easier to deal with than a new entity. With complex types you do not have to deal with the Primary Key. Think about accessing an address how many common types of entities would have an address (Business Units, People, Places). Imagine populating many peoples addresses and needing to set a key for each one. With complex types you simply access the internal properties of they type and you're done. Here is an MSDN link of an example. http://msdn.microsoft.com/en-us/library/bb738613.aspx
This question has been here a while already, but I'm going to add an answer anyway in the hopes that the next poor sob that comes along knows what he's in for.
Complex types do not support lazy loading, at least not in EF 4.3. Let's take the address situation as an example. You have a Person table with 15 columns, 5 of which contain address information for certain individuals. It has 50k records. You create entity Person for the table with a complex type Address.
If you need a list of names of all individuals in your database you would do
var records = context.Persons;
which also includes addresses, pumping 5*50k values into your list for no reason and with noticeable delay. You could opt to only load the values you need in an anonymous type with
var records = from p in context.Persons
select new {
LastName = p.LastName,
FirstName = p.FirstName,
}
which works well for this case, but if you needed a more comprehensive list with, say, 8 non-address columns you would either need to add each one in the anonymous type or just go with the first case and go back to loading useless address data.
Here's the thing about anonymous types: While they are very useful within a single method, they force you to use dynamic variables elsewhere in your class or class children, which negate some of Visual Studio's refactoring facilities and leave you open to run-time errors. Ideally you want to circulate entities among your methods, so those entities should carry as little baggage as possible. This is why lazy loading is so important.
When it comes to the above example, the address information should really be in a table of its own with a full blown entity covering it. As a side benefit, if your client asks for a second address for a person, you can add it to your model by simply adding an extra Address reference in Person.
If unlike the above example you actually need the address data in almost every query you make and really want to have those fields in the Person table, then simply add them to the Person entity. You won't have the neat Address prefix any more, but it's not exactly something to lose sleep over.
But wait, there's more!
Complex types are a special case, a bump on the smooth landscape of plain EF entities. The ones in your project may not be eligible to inherit from your entity base class, making it impossible to put them through methods dealing with your entities in general.
Assume that you have an entity base class named EntityModel which defines a property ID. This is the key for all your entity objects, so you can now create
class EntityModelComparer<T> : IEqualityComparer<T> where T : EntityModel
which you then can use with Distinct() to filter duplicates from any IQueryable of type T where T is an entity class. A complex type can't inherit from EntityModel because it doesn't have an ID property, but that's fine because you wouldn't be using distinct on it anyway.
Further down the line you come across a situation where you need some way to go through any entity and perform an operation. Maybe you want to dynamically list the properties of an entity on the UI and let the user perform queries on them. So you build a class that you can instantiate for a particular type and have it take care of the whole thing:
public class GenericModelFilter<T> : where T : EntityModel
Oh wait, your complex type is not of type EntityModel. Now you have to complicate your entity inheritance tree to accommodate complex types or get rid of the EntityModel contract and reduce visibility.
Moving along, you add a method to your class that based on user selections can create an expression that you can use with linq to filter any entity class
Expression<Func<T, bool>> GetPredicate() { ... }
so now you can do something like this:
personFilter = new GenericModelFilter<Person>();
companyFilter = new GenericModelFilter<Company>();
addressFilter = new GenericModelFilter<Address>(); //Complex type for Person
...
var query = from p in context.Persons.Where(personFilter.GetPredicate())
join c in context.Companies.Where(companyFilter.GetPredicate()) on p.CompanyID = c.ID
select p;
This works the same for all entity objects... except Address with its special needs. You can't do a join for it like you did with Company. You can navigate to it from Person, but how do you apply that Expression on it and still end up with Person at the end? Now you have to take moment and figure out this special case for a simple system that works easily everywhere else.
This pattern repeats itself throughout the lifetime of a project. Do I speak from experience? I wish I didn't. Complex types keep stopping your progress, like a misbehaved student at the back of the class, without adding anything of essence. Do yourself a favor and opt for actual entity objects instead.
Based on Domain Driven Design Concepts, Aggregate root could have one or more internal objects as its parts. In this case, Internal objects - inside the boundary of Aggregate Root - does not have any KEY. The parent key will be applied to them or somehow like this. Your answer returns to the benefit of keeping all Parts inside Aggregate root that makes your model more robust and much simpler.