user1917176
user1917176

Reputation:

Deleting a Many-to-Many Navigation Property

I have three tables:-

SecurityRole & Groups & SecurityRoleGroups. (securityrole can have many groups. and a group can have many securityroles)

where the SecurityRoleGroup table is a many-to-many relation table, and Entity framework will not map this table . so i want to remove all the SecurityRoleGroup records that belong to certain SecurityRole. if i write something as

SecurityRole securityrole = FindAllRole(id);

tms.SecurityRoles.Remove(securityrole).Groups.Where(a=> a.GroupID == group.GroupID)

will it remove only the needed records from the SecurityRoleGroup, ot it will also remove the related SecurityRole record ?

:::UPDATE:::

But what if I want to delete the Many-To-Many record only incase it is inside the currentGroups[c] array. can I write something as follow:-

 if (group.GroupID == currentGroups[c])
                            {
var securityrole = tms.SecurityRoles.Where(a => a.SecurityRoleID == id).Include(p => p.Groups).SingleOrDefault();

    (securityrole != null) {

    securityrole.Groups.Remove(group);

                                }
                            }

Upvotes: 1

Views: 282

Answers (1)

Slauma
Slauma

Reputation: 177163

If you want to remove only the relationships stored in the link table, not the entities SecurityRole and Groups, the entities must be attached to the context in the current relationship (i.e. the Groups must be in the Groups collection of the SecurityRole entity) and then you must remove them from this collection. EF will track this change and write DELETE statements to the link table alone.

It can be achieved like so:

using (var context = new MyContext())
{
    var securityRole = context.SecurityRoles
        .Include(s => s.Groups)  // or Include("Groups") for EF <= 4.0
        .SingleOrDefault(s => s.SecurityRoleId == givenId);

    if (securityRole != null)
    {
        securityRole.Groups.Clear();
        context.SaveChanges();
    }
}

Edit

If you want to remove only link records that fulfill a given condition use Remove instead of Clear:

    if (securityRole != null)
    {
        foreach (var group in securityRole.Groups
            .Where(g => currentGroups[c].Contains(g.GroupID)).ToList())
        {
            securityRole.Groups.Remove(group);
        }
        context.SaveChanges();
    }

(assuming that currentGroups[c] is a collection of group IDs)

Upvotes: 1

Related Questions