我有一组相当简单的数据库表,例如:
Vehicle
Id
RegNo
Car
Id (FK of Vehicle.Id)
OtherStuff
Bike
Id (FK of Vehicle.Id)
MoreStuff
我的类模型正如您所期望的那样:Vehicle是一个抽象类,然后Car和Bike是它的子类。
我已经设置了我的EF4.1 Code First配置如下:
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);
}
}
但是当EF尝试构建其模型配置时,我遇到了许多奇怪的例外。
目前它正在抛弃这个:
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'.
它从哪里获取列名?它不在我的任何代码或数据库本身。它必须是一些接管控制的惯例。如何指示EF使用每个表格类型?
如果我从我的Vehicle类中删除“abstract”关键字(我在线上的某个地方进行了一次完整性测试),那么我会得到一个不同的异常,如下所示:
(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.
我显然做了一件非常糟糕的事情,但是什么呢?我已经关注了MSDN文档以及我能找到的所有其他TPT + EF4.1文章!
你看过下面的文章了吗?
这是一篇包含以下方法的3部分文章
当我遇到这个问题时,我发现我有一个未映射的子类。在此示例中,一些可能的原因是:
Bus
。这没有映射。Car
,未映射。在这种情况下,请确保映射每个子类:
ToTable
方法调用。OnModelCreating
期间实际应用映射。或者,如果不应该首先映射子类,请确保使用其中一个Ignore
方法调用忽略它。