简单模型中的EF6外键约束

时间:2014-09-02 08:46:03

标签: c# foreign-keys asp.net-mvc-5 virtual dbset

我正在编写一个简单的MVC 5互联网应用程序。这是我的模特:

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; }
}

当我在House控制器中加载Index动作结果时,我收到此错误:

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; }
}

我仍然遇到同样的错误。

1 个答案:

答案 0 :(得分: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);
}