Can ADO.NET Entity Framework provide collections of child classes instead of the parents?
I'm starting to work with ADO.NET Entity M开发者_如何学编程odels, and all of my objects share a few common fields, such as FileAs
(the primary key), SourceURL
, Name
, and Description
. Other than these fields, they are all very different. At first, I implemented them using an abstract Reference
class, containing the above fields, and having all my other objects inherit that. This, however, forces me me to query every one of my objects like this:
foreach (MyObject obj in context.References.Where(o=>o is MyObject)) { ... }
I don't want to search through every one of my Reference
s to find all of MyObjects
, and want a way to simply call foreach (var obj in context.MyObjects) { ... }
.
I could just add the shared properties to each of MyObject
classes, but then FileAs
will not be unique between all MyObject1
s and MyObject2
s. I could do a 0..1
to 1
relationship between Reference
and all MyObject
s, but this would let one Reference
apply to several different MyObject
s of different types.
If you are using default entity generation with EF custom tool (it will created .Designer.cs file under your EDMX) or T4 template generating entities derived from EntityObject
there is probably no way to achieve that without having the base entity. The problem is that all entities generated by these tools must inherit from EntityObject
. If you want to define your own base class you must inherit it from EntityObject
as well and because of that you must map it. Using entity inheritance model for this scenario has much more drawbacks then querying. For example each entity PK must be unique across all entities.
It should be possible with POCO entities which doesn't have any base class. You can define your own base class and modify T4 template to use that class as the parent for each entity. This will not solve the problem in EDMX - you will still have to define and map shared properties in each single entity in the designer (designer will not know about the parent class).
POCOs and T4 templates are only features of EFv4 (VS 2010).
精彩评论