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

Entity framework 为什么Remove()不从数据库中删除实体?,entity-framework,Entity Framework,在试图找出如何在Entity Framework中从数据库中删除实体时,google中几乎所有的hit都告诉我需要使用Remove()。例如: 事实并非如此。这只会孤立实体。在我的ReportComment中,它试图将指向其子报表的外键设置为null,这会导致应用程序崩溃,因为外键设置为非null。我解决这个问题的方法如下: 首先在我的服务中创建GetContext: public IRiskAliveContext GetContext() { return _context; } 然后我在

在试图找出如何在Entity Framework中从数据库中删除实体时,google中几乎所有的hit都告诉我需要使用Remove()。例如:

事实并非如此。这只会孤立实体。在我的ReportComment中,它试图将指向其子报表的外键设置为null,这会导致应用程序崩溃,因为外键设置为非null。我解决这个问题的方法如下:

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

public IRiskAliveContext GetContext()
{
return _context;
}
然后我在控制器中调用此函数:

IRiskAliveContext context = _projectService.GetContext();
然后我使用上下文调用Entry(),然后将条目的状态设置为Deleted:

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

我为什么要这样做?为什么Remove()不能像google所说的那样工作?

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

大致上,您可以“从该报告中删除此注释”,而不是“从数据库中删除此注释”

因此,请尝试以下方法:

context.ReportComments.Remove(comment);
而不是

report.ReportComments.Remove(comment);

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

大致上,您可以“从该报告中删除此注释”,而不是“从数据库中删除此注释”

因此,请尝试以下方法:

context.ReportComments.Remove(comment);
而不是

report.ReportComments.Remove(comment);