我在Entity Framework Code First项目中有以下删除方法:
var selectedID = selectedGroup.ID;
var users = (from user in db.Users
where user.Group_ID == selectedID
select user);
db.Users.RemoveRange(users);
db.Groups.Attach(selectedGroup);
db.Groups.Remove(selectedGroup);
db.SaveChanges();
这些是模型:
public class Group
{
[Key]
public Guid ID { get; set; }
[Required]
public Guid Branch { get; set; }
}
public class User
{
[Key]
public Guid ID { get; set; }
[Required]
public Guid Group_ID { get; set; }
}
调用db.SaveChanges()时,我得到一个异常:
The DELETE statement conflicted with the REFERENCE constraint
“FK_Users_Groups”. The conflict occurred in database “UserDB”, table
“dbo.Users”, column ‘Group_ID’. The statement has been terminated.
似乎以反向(随机)顺序调用Remove方法.如果我在RemoveRange()之后添加另一个db.SaveChanges(),它(显然)可以正常工作.
我如何强制删除命令?
最佳答案 你需要教EF表关系.然后它会自动为您订购DML操作.声明模型中的关系.例如,用户类应具有组属性.
这些属性在查询中也非常有用.没有它们,不确定你是如何做到的.手动编写连接很繁琐.