具有以下实体:
public class Driver
{
public LocationMonitor locationMonitor {get;set;}
... some other properties...
}
public class LocationMonitor
{
public Location actualLocation {get; set;}
public Location previousLocation {get;set;}
}
public class Location
{
public LocationTypeEnum locationEnum {get;set;}
public int? locationPointId {get;set;} // foreign key
public LocationPoint locationPoint {get;set;} // navigation property
}
我希望表驱动程序带有列
int location // LocationTypeEnum
int actualLocationPointId // (nullable) foreign key to LocationPoint table
int previousLocation // LocationTypeEnum
int prevoiusLocationPointId // (nullable) foreign key to LocationPoint table
如何使用Fluent API做到这一点?
我尝试使用IEntityTypeConfiguration派生类通过Fluent API对其进行配置:
...
driverBuilder.OwnsOne(driver => driver.locationMonitor,
lmBuilder => {
lmBuilder.OwnsOne(lm => lm.actualLocation,
location => {
location.Property(l => l.locationEnum).HasColumnName("location");
location.Property(l => l.locationPointId).HasColumnName("locationPointId");
location.HasOne(l => l.locationPoint)
.WithMany()
.HasForeignKey("locationPointId");
});
lmBuilder.OwnsOne(lm => lm.previousLocation,
location => {
location.Property(l => l.locationEnum).HasColumnName("previousLocation");
location.Property(l => l.locationPointId).HasColumnName("previousLocationPointId");
location.HasOne(l => l.locationPoint)
.WithMany()
.HasForeignKey("previousLocationPointId");
});
});
...
但在创建迁移时有以下警告:
There are multiple relationships between 'Driver' and 'LocationPoint' without configured foreign key properties causing EF to create shadow properties on 'Driver' with names dependent on the discovery order.
在生成的迁移中,创建了5个“外键”列,其名称为:LocationPointID, LocationPointID1, locationPointId, previousLocationPointId, locationMonitor_previousLocation_previousLocationPointId
,并为列定义了4个外键:LocationPointID, LocationPointID1, locationPointId, locationMonitor_previousLocation_previousLocationPointId
我试图像这样在OwnsOne定义的“外部”定义外键:
driverBuilder.HasOne(driver => driver.locationMonitor.actualLocation.locationPoint)
.WithMany()
.HasForeignKey("locationPointId");
但是Fluent API不允许定义这种复杂的导航属性。
在OwnsOne
定义(嵌套)中定义它们时,如何使其仅生成具有给定列名的2个外键?在互联网上搜索了很长时间,我没主意了。任何帮助表示赞赏。
在@IvanStoev发表评论后编辑
您是对的@IvanStoev,我在LocationPoint中引用了Driver实体:
public ICollection<Driver> actualLocationDrivers {get;set;}
public ICollection<Driver> previousLocationDrivers {get;set;}
这是不必要的。他们甚至都没有配置。删除它们后,它就像一种魅力。