Reputation: 43
Entity Framework 6 by default when it meets inheritance creates a special entity hierarchy with either TPH, TPT or TPC. But I would like EF to treat my classes as completely separate entities.
I have the following classes hierarchy where each class is mapped to a View in DB:
[Table("v_Item")]
class Item
{
[Key]
public int ID { get; set; }
public string Name { get; set; }
}
[Table("v_ItemWithDescription")]
class ItemWithDescription : Item
{
public string Description { get; set; }
}
This design makes it possible to get more detailed info when needed. And it is so DRY. It is also nice to cast IQueryable
:
IQueryable<ItemWithDescription> query = ...;
((IQueryable<Item>) query).Where(i => i.Name == "Foo")
But EF insists on adding discriminator column and badly distorts the queries. And there seems to be no way to make EF just forget that these classes have inheritance hierarchy!
Adding discriminator column to views and switching to TPC does not help as there appear lots of UNION
s in a query. It seems that my only option is to modify EF source code if I want to stick to my inherited approach. Are there any simpler solutions?
Thanks in advance!
Upvotes: 1
Views: 388
Reputation: 5159
If you don't map the base entity, it ignores the inheritance. So here's a trick you can do:
Create a base class for your Item
class and pull all members up. Let's call it ItemBase
. Do not map this class, and do not add it to your DbContext
.
Then Item
will be a mapped class without any properties of its own (will inherit everything from the base class). Make the rest of the classes (like ItemWithDescription
) extend the ItemBase
too.
This way, you'll have the code re-use, but lose the inheritance relationship between Item
and its children, which depending on your case, may or may not be acceptable.
Upvotes: 1