2015-11-15 54 views
2

試圖運行我的MVC應用程序EF CodeFirst - 不能創建數據庫

Introducing FOREIGN KEY constraint 'FK_dbo.Passages_dbo.Localizations_ToID' on table 'Passages' 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 or index. See previous errors' 

I`ve看到很多帖子我得到的錯誤,但我無法得到我應該怎麼辦。 有我的模型:

public class Passage 
    { 
     [Key] 
     public int ID { get; set; } 
     public int FromID { get; set; } 
     [ForeignKey("FromID")] 
     public Localization FromLocalizaton { get; set; } 
     public int ToID { get; set; } 
     [ForeignKey("ToID")] 
     public Localization ToLocalization { get; set; } 
     public DateTime DepartureTime { get; set; } 
     public DateTime ArrivalTime { get; set; } 
     public DateTime? AdditionalTime { get; set; } 
     public bool Weekend { get; set; } 
     public int Seats { get; set; } 
    } 


public class Localization 
{ 
    [Key] 
    public int ID { get; set; } 
    public string Province { get; set; } 
    public string City { get; set; } 
    public string PostalCode { get; set; } 
    public string StreetAdres { get; set; } 
} 

通道有兩個外鍵是指具有一一對應的關係

回答

1

問題從這次來到Lozalization:

通道有兩個外鍵是指Lozalization與一對一的關係

因爲默認情況下這兩個關係是在Passage(看外鍵FromIDToID沒有Nullable<int>int?),因此代碼首先在這些關係上創建級聯刪除操作。但是,兩個級聯刪除將應用於不允許的同一個表上。

要解決此問題,有兩種解決方法:

讓外國鍵屬性Nullable<int>在默認情況下不會產生級聯刪除該關係的行動之一。

或者,您可以禁用級聯使用流利的API這樣的刪除操作:

// Assuming that you want to disable cascade deletion with ToLocalization 
modelBuilder.Entity<Passage>() 
      .HasRequired(p => p.ToLocalization) 
      .WithMany() 
      .WillCascadeOnDelete(false);