2014-09-02 54 views
0

我正在編寫一個簡單的MVC 5互聯網應用程序。這裏是我的模型:簡單模型中的EF6外鍵約束

public class House 
{ 
    [Key] 
    public int Id { get; set; } 
    public string name { get; set; } 
    public virtual ICollection<Room> rooms { get; set; } 
    public int itemId { get; set; } 
    public virtual Item item { get; set; } 

    public House() 
    { 
     rooms = new List<Room>(); 
    } 
} 

public class Room 
{ 
    [Key] 
    public int Id { get; set; } 
    public int roomNumber { get; set; } 

    public int houseId { get; set; } 
    public virtual House house { get; set; } 

    public int itemId { get; set; } 
    public virtual Item item { get; set; } 
} 

public class Item 
{ 
    [Key] 
    public int Id { get; set; } 
    public string name { get; set; } 
} 

當我加載在衆議院的控制指標作用的結果,我收到此錯誤:

Introducing FOREIGN KEY constraint 'FK_dbo.Rooms_dbo.Items_itemId' on table 'Rooms' 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. 

我可以請有一定的幫助,以正確的代碼呢?

在此先感謝

編輯

我現在已經添加了ForeignKey屬性的字段外鍵的字段:

public class House 
{ 
    [Key] 
    public int Id { get; set; } 
    public string name { get; set; } 
    public virtual ICollection<Room> rooms { get; set; } 
    public int itemId { get; set; } 
    [ForeignKey("itemId")] 
    public virtual Item item { get; set; } 

    public House() 
    { 
     rooms = new List<Room>(); 
    } 
} 

public class Room 
{ 
    [Key] 
    public int Id { get; set; } 
    public int roomNumber { get; set; } 

    public int houseId { get; set; } 
    [ForeignKey("houseId")] 
    public virtual House house { get; set; } 

    public int itemId { get; set; } 
    [ForeignKey("itemId")] 
    public virtual Item item { get; set; } 
} 

public class Item 
{ 
    [Key] 
    public int Id { get; set; } 
    public string name { get; set; } 
} 

我仍然得到同樣的錯誤。

+0

多少ID的你需要,項目Id和項目在房間對象中標識的屬性。 – Lloyd 2014-09-02 08:52:46

+0

ItemId用於Item對象,Id是整個Room對象的主鍵。 – user3736648 2014-09-02 10:45:58

回答

1

我已經想通了。我需要禁用上下文類中的級聯刪除。

下面是代碼:

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
{ 
    modelBuilder.Entity<House>() 
     .HasRequired(c => c.item) 
     .WithMany() 
     .WillCascadeOnDelete(false); 

    modelBuilder.Entity<Room>() 
     .HasRequired(s => s.item) 
     .WithMany() 
     .WillCascadeOnDelete(false); 
}