2
votes

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

3

3 Answers

2
votes

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

1
votes

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

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

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