2011-04-03 124 views
35

我正在使用代码设计我的数据库,我需要一点帮助。实体框架代码首先定义关系/键

我收到此错误:

Introducing FOREIGN KEY constraint 'SalesOrder_Invoices' on table 'Invoices' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Could not create constraint. See previous errors.

我想有以下关系/键:

--> = 1 to Many Relationship 
  1. 客户 - > CustomerLocation
  2. CustomerLocation - > SalesOrder
  3. SalesOrder - >发票
  4. 的SalesRep - > SalesOrder
  5. PaymentTerm - >客户
  6. PaymentTerm - > SalesOrder
  7. PaymentTerm - >发票

我试图去界定按以下标准:

<ClassName><PrimaryKeyID> 

例如:CustomerID属性,所以在CustomerLocation我定义了外键,像这样:

Public Property CustomerID AS Integer 

所有我需要做的就是定义外键是否正确?我是否也必须为每个我定义的键拥有导航属性?

而且,我可以在一个对象的同一主键上没有多个外键吗?

更新

所以要定义一个关系,你用的ClassName.PrimaryKeyProperty?或者你使用导航属性?或两者?困惑!!

更新2

因此,为了使你必须定义双方的关系的工作......我想。

Public Class Customer 
    Public Property ID AS Integer 
    Public Overrideable Property Locations AS ICollection(OF CustomerLocation) 

End Class 

Public Class CustomerLocation 
    Public Property ID AS Integer 
    Public Property CustomerID AS Integer 

End Class 

回答

95

当您有多个级联删除路径时,这是由SQL Server引起的异常。如果您删除了PaymentTerm,它将触发所有三种关系的级联删除。当创建SalesOrderInvoice时,这将会炸毁。EF默认创建与ON DELETE CASCADE都是一个一对多的关系,你可以重新映射你的特定关系,以不使用它:

modelBuilder.Entity<...>() 
      .HasRequired(...) 
      .WithMany(...) 
      .HasForeignKey(...) 
      .WillCascadeOnDelete(false); 

或者,您可以通过删除惯例globaly将其关闭:

modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>(); 

AddForeignKey("dbo.Payments", "EventID", "dbo.Events", "EventID", cascadeDelete: true) 

,改变日:

您可以用一条线是这样的编辑产生Up()方法解决这个错误在特定迁移在cascadeDelete:价值对错误的关系(S)。

+0

因此,要建立一个关系的工作,你必须定义双方?请参阅我上面的更新。 – Sam 2011-04-04 00:12:10

+0

@Sam:不,你不需要双方的导航属性。 – 2011-04-04 06:16:15

+13

我喜欢'OneToManyCascadeDeleteConvention'提示这个答案。 – batwad 2012-01-31 16:54:17

4

this,我相信这将帮助你找到答案。

另外,根据ScottGu的blogpost,我想一般应该是您刚才创建的类如下(我也没有看过足够仔细,所以你应该检查出来的其他细节):

public class Customer 
{ 
    public int CustomerID { get; set; } 
    public int CustomerLocationID { get; set; } 
    public virtual CustomerLocation Location { get; set; } 
} 

public class CustomerLocation 
{ 
    public int CustomerLocationID { get; set; } 
    public virtual ICollection<Customer> Customers { get; set; } 
} 
相关问题