2013-04-01 53 views
2

我發展與實體框架代碼優先一個asp.net mvc的解決方案,我得到了錯誤:循環或多個級聯路徑錯誤

Introducing FOREIGN KEY constraint 'FK_dbo.Transports_dbo.Shippers_ReceiverId' on table 'Transports' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.

開始在該解決方案時發生這種情況數據庫的創建過程。

這裏是我的模型:

public class Transport 
{ 
    [Key] 
    public int Id { get; set; } 
    ... 
    public int SenderId { get; set; } 
    public int ReceiverId { get; set; } 
    ... 
    public virtual Shipper Sender { get; set; } 
    public virtual Shipper Receiver { get; set; } 
} 

public class Shipper 
{ 
    [Key] 
    public int Id { get; set; } 
    public string Name { get; set; } 
    public string Street { get; set; } 
    public string Number { get; set; } 
} 

如果我評論的public virtual Shipper Receiver { get; set; }那麼它的工作原理,所以這是循環的問題。

有沒有人可以幫助我解決這個問題?

回答

2

對於更復雜的「自我約束」或「多重相同」關係,您需要明確定義關係 - 最好使用流暢配置。

例如

modelBuilder.Entity<Transport>() 
    .HasRequired(at => at.Sender) 
    .WithMany(a => a.TransportsAsSender) 
    // .HasForeignKey(at => at.SenderId) 
    .WillCascadeOnDelete(false); 

modelBuilder.Entity<Transport>() 
    .HasRequired(at => at.Receiver) 
    .WithMany(a => a.TransportsAsReceiver) 
    // .HasForeignKey(at => at.ReceiverId) 
    .WillCascadeOnDelete(false); 

...這假定您還添加:

public ICollection<Transport> TransportsAsSender { get; set; } 
public ICollection<Transport> TransportsAsReceiver { get; set; } 

...到Shipper

或者只是使用...

.WithMany() // and no collection navigation properties 
相關問題