【发布时间】:2016-07-22 03:20:09
【问题描述】:
我正在使用带有代码优先方法的实体框架。
在我的onModelCreating 中,我正在使用键和关系创建表(我使用的是 Fluent API 方法,而不是数据注释)。
但是当我尝试使用Update-Database 命令生成我的模型时,我收到以下错误
在表“发票”上引入 FOREIGN KEY 约束“FK_customers.invoices_customers.billingCenters_billingCenterId”可能会导致循环或多个级联路径。指定 ON DELETE NO ACTION 或 ON UPDATE NO ACTION,或修改其他 FOREIGN KEY 约束。无法创建约束。查看以前的错误。
我几乎可以肯定我没有循环......如果我有级联路径,我不会有问题。这是我想要的!
按照我正在创建的模型:
modelBuilder.Entity<Customer>()
.ToTable("customers", schemaName)
.HasKey(c => new { c.Code });
modelBuilder.Entity<BillingCenter>()
.ToTable("billingCenters", schemaName)
.HasKey(bc => new { bc.Id });
//1 Customer -> N BillingCenters
modelBuilder.Entity<BillingCenter>()
.HasRequired(bc => bc.Customer)
.WithMany(c => c.BillingCenters)
.HasForeignKey(bc => bc.CustomerId);
modelBuilder.Entity<Invoice>()
.ToTable("invoices", schemaName)
.HasKey(i => new { i.Id });
//Here the code gives me problems
//1 BillingCenter -> N Invoices
modelBuilder.Entity<Invoice>()
.HasRequired(i => i.BillingCenter)
.WithMany(bc => bc.Invoices)
.HasForeignKey(i => i.BillingCenterId);
modelBuilder.Entity<Payment>()
.ToTable("payments", schemaName)
.HasKey(ep => new { ep.Id })
.Property(ep => ep.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
//1 Customer -> N Payments
modelBuilder.Entity<Payment>()
.HasRequired(ep => ep.customer)
.WithMany(c => c.Payments)
.HasForeignKey(ep => ep.customerCode);
//1 Invoice -> N Payments (Failed, Ok, ...)
modelBuilder.Entity<Payment>()
.HasRequired(p => p.Invoice)
.WithMany(i => i.Payments)
.HasForeignKey(p => p.InvoiceId);
如果我删除此代码,一切似乎都正常
modelBuilder.Entity<Invoice>()
.HasRequired(i => i.BillingCenter)
.WithMany(bc => bc.Invoices)
.HasForeignKey(i => i.BillingCenterId);
并生成以下数据库:
我说它似乎可以工作,因为如果我看到 billingCenters 和 invoices 之间的关系,delete rule 就是 no action。
我该如何解决这个问题?
提前谢谢你
【问题讨论】:
标签: entity-framework foreign-keys foreign-key-relationship cascade