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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With