引用约束错误删除具有集合导航属性的派生类型 [英] Reference constraint error deleting derived type having collection navigation property

查看:54
本文介绍了引用约束错误删除具有集合导航属性的派生类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我得到  DELETE语句与REFERENCE约束冲突 错误尝试删除包含其他对象列表的对象  ;  从映射到单独表的其他类型派生

I get a The DELETE statement conflicted with the REFERENCE constraint error trying to delete an object that contains a list of other objects and derives from an other type that is mapped to a separate table.


Here是我的类型:

Here are my types:

public class Base
{
    public int Id { get; set; }
}

public class Main : Base
{
    public virtual IList<ListItem> ListItems { get; set; }
}

public class ListItem
{
    public int Id { get; set; }

    public int MainId { get; set; }
    public virtual Main Main { get; set; }
}



配置:

configuration:

public DbSet<Base> Bases { get; set; }
public DbSet<Main> Mains { get; set; }
public DbSet<ListItem> ListItems { get; set; }

modelBuilder.Entity<Base>().ToTable("SomeTable");
modelBuilder.Entity<Main>().HasKey(x => x.Id)
               .HasMany(x => x.ListItems)
               .WithRequired(x => x.Main)
               .WillCascadeOnDelete();



我删除Main的方式:

The way I delete Main:

context.Entry(context.Main.First()).State = EntityState.Deleted;
context.SaveChanges();



如果基类是  not mapped  到表。这非常奇怪。我在这里做错了什么?我试过覆盖Base类型的Id属性,我甚至尝试移动
Id属性为Main类型并将其从Base中删除,但没有运气。

I don't get any error if Base class is not mapped to a table. This is extremely weird. What am I doing wrong here? I tried overriding the Id property of the Base type, I even tried moving the Id property to the Main type and removing it from the Base altogether, but no luck.

推荐答案

嗨ewzer,

Hi ewzer,

根据您的描述和代码片段,我们知道,实体框架依赖于每个具有用于跟踪实体的密钥值的实体。从您的代码中,我找不到名为Main的模型上的任何键。我检索到这样的错误:

Based on your description and code snippet, As we know, Entity Framework relies on every entity having a key value that it uses for tracking entities. From your code, I could not find any key on model named Main. I retrieve a error like this:

请修改您的模型如下:

public class Main : Base
{
    public virtual IList<ListItem> ListItems { get; set; }
}

public class Main {

public int Id {get; set;}
公共虚拟IList< ListItem> ListItems {get;组; }
}

public int Id { get; set; } public virtual IList<ListItem> ListItems { get; set; } }

祝你好运,

Cole Wu


这篇关于引用约束错误删除具有集合导航属性的派生类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆