gpt4 book ai didi

entity-framework - EF - 级联删除不起作用,无法删除对象

转载 作者:行者123 更新时间:2023-12-04 13:04:47 25 4
gpt4 key购买 nike

我收到此错误:

System.Data.SqlClient.SqlException The DELETE statement conflicted with the REFERENCE constraint "FK_comments_postId__164452B1". The conflict occurred in database "awe", table "dbo.comments", column 'postId'. The statement has been terminated.



我有这个结构:
    public class Post
{
public long Id { get; set; }
public string Body { get; set; }

public long? ParentId { get; set; }
public virtual Post Parent { get; set; }
public virtual ICollection<Post> Posts { get; set; }

public virtual ICollection<Comment> Comments { get; set; }
}

public class Comment
{
public long Id { get; set; }
public long PostId { get; set; }
public virtual Post Post { get; set; }
public string Body { get; set; }
}

我的删除方法:
    public void Delete(long id)
{
var p = context.Set<Post>().Get(id);
if(p == null) throw new MyEx("this post doesn't exist");
if (p.Posts.Count > 0) throw new MyEx("this post has children and it cannot be deleted");
context.Set<Post>().Remove(p);
context.SaveChanges();
}

我的数据库上下文:
public class Db : DbContext
{
public DbSet<Post> Posts { get; set; }
public DbSet<Comment> Comments { get; set; }
}

最佳答案

听起来您要删除的帖子有子评论。

Entity Framework 不负责在数据库中级联删除 - 它希望您通过在 RDBMS 中的外键关系上设置级联删除来实现这一点。

话虽如此,如果您删除 Entity Framework 中的父实体,它将尝试为已加载到当前 DbContext 中的任何子实体发出删除语句,但它不会初始化任何尚未加载的子实体 .如果未指定级联删除,这可能会导致 RDBMS 抛出外键约束违规异常,就像您看到的那样。有关级联删除如何在 Entity Framework 中“工作”的更多详细信息,see this blog post .

关于entity-framework - EF - 级联删除不起作用,无法删除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7555645/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com