开发者

can't delete object that has a many-to-many relationship

开发者 https://www.devze.com 2023-02-13 04:22 出处:网络
these are my simplified entities: public class User : Entity { public virtual ICollection<Role> Roles { get; set; }

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 n开发者_StackOverflowoticed 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


You must first clear Roles collection (user's roles must be loaded) before you will be able to remove user.


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


user.Roles
    .ToList()
    .ForEach(role => user.Roles.remove(role));

context.Users.remove(user);
context.SaveChanges();
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号