为什么Remove()不会从数据库中删除实体?

时间:2017-09-06 23:48:20

标签: entity-framework

在尝试弄清楚如何从Entity Framework中的数据库中删除实体时,Google中几乎所有人都告诉我需要使用Remove()。如:

ReportComment comment = report.ReportComments.LastOrDefault();
report.ReportComments.Remove(comment);

事实并非如此。这只是实体的孤儿。在我的ReportComment的情况下,它尝试将指向它的子报告的外键设置为null,这会导致应用程序崩溃,因为外键设置为非null。我必须解决的问题如下:

首先在我的服务中创建GetContext:

public IRiskAliveContext GetContext()
{
return _context;
}

然后我在我的控制器中调用此函数:

IRiskAliveContext context = _projectService.GetContext();

然后我使用上下文调用Entry(),然后将Entry的状态设置为Deleted:

ReportComment comment = report.ReportComments.LastOrDefault();
report.ReportComments.Remove(comment);
context.Entry(comment).State = EntityState.Deleted;

为什么我需要这样做?为什么Remove()不像谷歌那样工作?

1 个答案:

答案 0 :(得分:1)

您正在导航属性report.ReportComments上调用ICollection.Remove,从数据库调用中删除DbSet.Remove

大概你有“从该报告中删除此评论”,而不是“从数据库中删除此评论”

所以尝试类似:

context.ReportComments.Remove(comment);

而不是

report.ReportComments.Remove(comment);
相关问题