级联删除错误

本文关键字:错误 删除 级联 | 更新日期: 2023-09-27 18:18:43

我已经编写了一个具有级联删除的MVC5互联网应用程序,并且得到以下错误:

Unable to cast object of type 'System.Collections.Generic.List`1[TestDeleteForeignKeyReferences.Models.Room]' to type 'TestDeleteForeignKeyReferences.Models.Room'.

这是我的上下文类:

public class MyDatabaseContext : DbContext
{
    public DbSet<House> houses { get; set; }
    public DbSet<Room> rooms { get; set; }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<House>()
            .HasOptional(x => x.rooms)
            .WithOptionalDependent()
            .WillCascadeOnDelete(true);
    }
}

这是我的House课程:

public class House
{
    [Key]
    public int Id { get; set; }
    public string name { get; set; }
    public virtual ICollection<Room> rooms { get; set; }
    public House()
    {
        rooms = new List<Room>();
    }
}

这是我的Room类:

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

尝试在以下创建代码中将House添加到数据库时发生错误:

db.houses.Add(house);

如果上下文类中没有OnModelCreating方法,则不会发生错误。

我能有一些帮助让这个代码工作吗?

级联删除错误

您想创建一个可选principal的one (house) to many (rooms)关系(house在room中是可选的)。配置应该像。

    modelBuilder.Entity<House>()
        .HasMany(x => x.rooms)
        .WithOptional(x => x.house)
        .WillCascadeOnDelete(true);