我有City实体:
public class City
{
public int ID { get; set; }
public string Name { get; set; }
public virtual ICollection<CityDistance> CityDistances { get; set; }
}
我希望保持城市之间的距离 1.如何在代码第一实体框架6中实现这一点?
以下是我的其他课程:
public class CityDistance
{
[Key, Column(Order = 0)]
public int CityAID { get; set; }
[Key, Column(Order = 1)]
public int CityBID { get; set; }
public virtual City CityA { get; set; }
public virtual City CityB { get; set; }
public double Distance { get; set; }
}
当我运行“add-migration Distances”时,结果就是这里 3.为什么要添加另一个名为“City_ID”的外键列?
CreateTable(
"dbo.CityDistances",
c => new
{
CityAID = c.Int(nullable: false),
CityBID = c.Int(nullable: false),
Distance = c.Double(nullable: false),
City_ID = c.Int(),
})
.PrimaryKey(t => new { t.CityAID, t.CityBID })
.ForeignKey("dbo.Cities", t => t.City_ID)
.ForeignKey("dbo.Cities", t => t.CityAID, cascadeDelete: true)
.ForeignKey("dbo.Cities", t => t.CityBID, cascadeDelete: true)
.Index(t => t.CityAID)
.Index(t => t.CityBID)
.Index(t => t.City_ID);
答案 0 :(得分:2)
那是因为EF就像一个简单的簿记员:CityA
,CityB
,这是两个外键,CityDistances
,这是另一个外键,它产生三个外键。
EF不知道您希望CityDistances
成为CityA
或CityB
关联的其他(反)结尾。您必须通过数据注释明确指出:
public class City
{
...
[InverseProperty("CityA"]
public virtual ICollection<CityDistance> CityDistances { get; set; }
}
或通过流利的映射:
modelBuilder.Entity<City>()
.HasMany(c => c.CityDistances)
.WithRequired(cd => cd.CityA)
.HasForeignKey(cd => cd.CityAID);
(我隐含地说,是的,这是正确的设计,至少在技术上)。