如何解决实体框架核心-在OwnsOne实体中设置外键列名称
具有以下实体:
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,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;}
这是不必要的。他们甚至都没有配置。删除它们后,它就像一种魅力。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。