无法删除具有多对多关系的对象
这些是我的简化实体:
public class User : Entity
{
public virtual ICollection<Role> Roles { get; set; }
}
public class Role : Entity
{
public virtual ICollection<User> Users { get; set; }
}
var user = dbContext.Set<User>().Find(id);
dbContext.Set<User>().Remove(user);
dbContext.SaveChanges(); // here i get error (can't delete because it's the
//referenced by join table roleUsers
问题是联接表引用用户表,并且 ef 在删除用户之前不会从联接表中删除记录
我尝试编写测试用例,我注意到:
如果使用相同的上下文添加具有角色的用户,保存更改,删除并再次保存更改,它可以工作,
但如果我使用 2 个不同的上下文,一个用于插入,另一个用于删除,我会收到此错误
these are my simplified entities:
public class User : Entity
{
public virtual ICollection<Role> Roles { get; set; }
}
public class Role : Entity
{
public virtual ICollection<User> Users { get; set; }
}
var user = dbContext.Set<User>().Find(id);
dbContext.Set<User>().Remove(user);
dbContext.SaveChanges(); // here i get error (can't delete because it's the
//referenced by join table roleUsers
the problems is that the join table references the user table and ef doesn't remove the records from the join table before deleting the user
I tried writing test cases and I noticed that:
if use the same context to add user with roles, save changes, remove and again save changes it works
but if I use 2 different contexts one for insert and another one for delete I get this error
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您必须先清除 Roles 集合(必须加载用户的角色),然后才能删除用户。
You must first clear Roles collection (user's roles must be loaded) before you will be able to remove user.
如果您只想删除此内容,只需按照错误提示执行即可。
作为 DELETE 方法的一部分,您应该按顺序执行此操作。
1) 获取 User 包括其相关角色,您可以使用 User.Include(r=>r.roles)
2) 迭代并删除给定用户的角色(确保在执行此循环时使用 toList() )
3) 删除用户
4) 保存更改
If you want to just get this deleting just do what the error is saying.
as a part of your DELETE method, you should do this, in order.
1) Get User including its related roles you can user User.Include(r=>r.roles)
2) iterate through and delete the roles for the given user (make sure you use a toList() when you do this loop )
3) Delete the user
4) savechanges