Hoda Osama
Hoda Osama

Reputation: 13

How to delete record in Many to Many table in EF without deleting the entities it self ?

I have two entities Users and Roles

public partial class User
{
 public int Id { get; set; }
    public string FirstName { get; set; }
    public string SecondName { get; set; }
    public virtual ICollection<Role> Roles { get; set; }

}

public partial class Role
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }    
    public virtual ICollection<User> Users { get; set; }
}

And i have table(RoleUser) in Database contain only userid and role id. I want to modify the user ,Delete the rows that exist in RoleUser Table and insert new record. When i used this following code it delete the rows in RoleUser Table and also the roles itself

   public void Update(User usr)
    {
        var existingParent = _context.Users
            .Where(p => p.Id == usr.Id)
            .Include(p => p.Roles)
            .SingleOrDefault();

        if (existingParent != null)
        {
            // Update parent
            _context.Entry(existingParent).CurrentValues.SetValues(usr);

            // Delete children
            foreach (var existingChild in existingParent.Roles.ToList())
            {
                if (!usr.Roles.Any(c => c.Id == existingChild.Id))
                    _context.Roles.Remove(existingChild);
            }
          }
        }

The question is how to delete the records that exist in RoleUser Table and insert new records without deleting the entities itself??

Upvotes: 0

Views: 3130

Answers (2)

nxt
nxt

Reputation: 26

This is code for remove

_context.Users.find(userId).Roles.Remove(_context.Roles.find(roleId));
_context.SaveChange();

And this is code for add

_context.Users.find(userId).Roles.Add(_context.Roles.find(roleId));
_context.SaveChange();

It will save userid and roleid to table many-to-many

Hope help you

Upvotes: 1

erikscandola
erikscandola

Reputation: 2936

You need to do this to remove a record only in Many to Many table. Let me know if it works for you.

IObjectContextAdapter contextAdapter = (IObjectContextAdapter)_context;
ObjectStateManager stateManager = contextAdapter.ObjectContext.ObjectStateManager;

stateManager.ChangeRelationshipState(existingParent, existingChild, "Roles", EntityState.Deleted);

_context.SaveChanges();

To add new values:

_context.Entry(existingParent).Collection("Roles").CurrentValue = values;

Where values is your list of data to add (should be IEnumerable or ICollection, so List<Role> is ok). values must contains object linked to database.

foreach (Role entry in newValues) {
    values.Add(_context.Set(typeof(Role)).Find(entry.Id));
}

Upvotes: 1

Related Questions