Each type inheritance using EF 4.1 Fluent Code First

I have a fairly simple set of database tables, for example:

Vehicle Id RegNo Car Id (FK of Vehicle.Id) OtherStuff Bike Id (FK of Vehicle.Id) MoreStuff 

My class model is the same as you would expect: with Vehicle, it is an abstract class, and then Car and Bike is a subclass.

I set up the configuration of the first EF4.1 code as follows:

 class VehicleConfiguration : EntityTypeConfiguration<Vehicle> { public VehicleConfiguration() { ToTable("Vehicles"); Property(x => x.Id); Property(x => x.RegNo); HasKey(x => x.Id); } } class CarConfiguration : EntityTypeConfiguration<Car> { public CarConfiguration() { ToTable("Cars"); Property(x => x.OtherStuff); } } class BikeConfiguration : EntityTypeConfiguration<Bike> { public BikeConfiguration() { ToTable("Bikes"); Property(x => x.MoreStuff); } } 

However, I get many weird exceptions when EF tried to build its model configuration.

He is currently throwing this:

 System.Data.EntityCommandExecutionException: An error occurred while executing the command definition. See the inner exception for details. ---> System.Data.SqlClient.SqlException: Invalid column name 'Discriminator'. 

Where does this column name come from? This is not in my code or the database itself. It must be some kind of agreement that requires control. How can I tell EF to use a table per type?

If I remove the "abstract" keyword from my Vehicle class (which I did as a sanity test somewhere along the line), then I get another exception, like the following:

 (35,10) : error 3032: Problem in mapping fragments starting at lines 30, 35:EntityTypes AcmeCorp.Car, AcmeCorp.Bike are being mapped to the same rows in table Vehicles. Mapping conditions can be used to distinguish the rows that these types are mapped to. 

I'm obviously doing something terrible, but what? I followed MSDN docs and all the other TPT + EF4.1 articles I can find!

+7
source share
2 answers

When I had this problem, I found that I have a subclass that was not mapped. In this example, some possible reasons for this are:

  • There is an additional subclass like Bus . This is not displayed.
  • One of the subclasses, such as Car , is not displayed.

In this case, make sure each subclass is displayed:

  • Make sure there is a mapping for the subclass, including a call to the ToTable method.
  • Make sure that the mapping does apply during OnModelCreating .
  • If you have trouble tracking this option, try using a debugger and set breakpoints in the entire display code.

Alternatively, if the subclass should not be displayed first, make sure that it is ignored using one of the Ignore method calls.

+8
source

Have you read the following article?

This is a three part article covering the following approaches.

+7
source

All Articles