只是为了解释Kjartans的解释:
我有:
public Project DeleteProject(int id)
{
using (var context = new Context())
{
var p = GetProject(id);
context.Projects.Remove(p);
context.SaveChanges();
return p;
}
}
问题是我使用了自己的方法(GetProject())来获取实体(因此使用另一个上下文来加载实体):
public Project GetProject(int id)
{
using (var context = new Context())
{
var project = context.Projects
.Include(p => p.Reports.Select(q => q.Issues.Select(r => r.Profession)))
.Include(p => p.Reports.Select(q => q.Issues.Select(r => r.Room)))
.SingleOrDefault(x => x.Id == id);
return project;
}
}
一种解决方案可能是按照Kjartan的说明附加已加载的实体,另一种可能是我的解决方案,以便在同一上下文中加载该实体:
public Project DeleteProject(int id)
{
using (var context = new Context())
{
var p = context.Projects.SingleOrDefault(x => x.Id == id);
if (p == null)
return p;
context.Projects.Remove(p);
context.SaveChanges();
return p;
}
}