Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework with interfaces does not work - what the best way to handle the same?

I am using Entity Framework and would like to use TPH with interfaces. So I have a created an interface, "ICustomer", which maps to "SimpleCustomer" and "DiscountedCustomer" class as shown below. Below is the model builder code. From what I understand we can not use interfaces with Entity Framework, so what's the best way?

 modelBuilder.Entity<ICustomer>().ToTable("tblCustomer")
.Map<SimpleCustomer>(x => x.Requires("CustomerType").HasValue("S"))
.Map<DiscountedCustomer>(x => x.Requires("CustomerType").HasValue("D"));

My application uses interfaces all over the UI and would like to have a smooth type casting to Entity Framework. So is what the best way?

like image 210
Shivprasad Koirala Avatar asked Apr 07 '15 02:04

Shivprasad Koirala


1 Answers

Entity Framework does not support TPH with interfaces (sorry for stating the obvious). This may not be the solution you are looking for, but I am still going to put it there because it seems to be the only solution as of 16 April 2015.

In Entity Framework 6, the closest you can get is - Use abstract classes instead of interfaces. This article talks about TPH in EF in great detail.

My suggestion is if you want to use interfaces and maintain the hierarchy and also still want smooth typecasting, consider using automapper with abstract classes. This way your UI will still use Interfaces, but can be mapped to domain model using automapper profiles. Atleast till the interface support arrives. It will not be a quick one if the application is large and has hundreds of domain models, so need to plan it wisely.

If you are creating it from scratch, you can simply use abstract classes from UI layer to DAL without any re-factoring.

like image 190
Bilal Fazlani Avatar answered Sep 26 '22 07:09

Bilal Fazlani