我有两个有关系的模型。
public class Customer
{
public Customer()
{
CustomerSites = new List<CustomerSite>();
}
public IList<CustomerSite> CustomerSites { get; set; }
}
public class CustomerSite
{
public Guid CustomerId { get; set; }
public Customer Customer { get; set; }
}
关系是由流利的 api 建立的:(我也尝试过只使用以下语句之一)
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<CustomerSite>()
.HasRequired(x => x.Customer)
.WithMany(x => x.CustomerSites)
.HasForeignKey(x => x.CustomerId);
modelBuilder.Entity<Customer>()
.HasMany(x => x.CustomerSites)
.WithRequired(x => x.Customer)
.HasForeignKey(x => x.CustomerId);
}
我的问题是为什么这段代码会生成数据库的双外键,如下例所示。
"dbo.CustomerSites",
c => new
{
CustomerId = c.Guid(nullable: false),
Customer_Id = c.Guid(),
})
.ForeignKey("dbo.Customers", t => t.CustomerId, cascadeDelete: true)
.ForeignKey("dbo.Customers", t => t.Customer_Id)
它应该只有一个 CustomerId 而不是 Customer_Id。如您所见,这也是可以为空的。如果我在 db 上下文中删除此列,则会在更新时引发异常。我觉得这很奇怪......