You load the person including its groups from the DB. Then you remove the group from the person's group collection (not from the context's group set (which would delete the whole group from the database)). Then you call SaveChanges
. EF will recognize that you have removed a group from the original person's group collection and send a DELETE statement to the database that deletes the join record from the PersonGroup
table:
public bool RemovePersonFromGroup(Guid personId, string groupName)
{
using (gblPersonEntities gblPerson = new gblPersonEntities())
{
var person = gblPerson.Person
.Include(p => p.Group)
.Where(p => p.PersonId == personId)
.SingleOrDefault()
if (person != null)
{
var group = person.Group
.Where(g => g.GroupName == groupName)
.FirstOrDefault();
if (group != null)
{
person.Group.Remove(group);
gblPerson.SaveChanges();
}
}
}
return true;
}