문제

I'm using Entity Framework 5 database first approach.

I have an existing database with these 3 tables: Person, Group, PersonGroup. This is to express a 1 to many relationship. A person can belong to multiple groups. The PersonGroup table has the IDs PersonId and GroupId.

Table structure:

Person: PersonId, PersonName

Group: GroupId, GroupName

PersonGroup: PersonId, GroupId

class diagram

EF5 has added the PersonGroup table as a navigation property on the Person and Group entites. I want to remove a person from a group based on the group name. I still want to keep the person and the group.

How do I write this method in the repository? Here's what I have that doesn't work

public bool RemovePersonFromGroup(Guid personId, string groupName)
    {

        using (gblPersonEntities gblPerson = new gblPersonEntities())
        {
            var pg = gblPerson.Person
                .Where(p => p.PersonId == personId).FirstOrDefault()
                .Group.Where(g => g.GroupName == groupName).FirstOrDefault();

           //doesn't work because pg returns as a Group entity and 
           //remove is expecting a Person entity and I just want to remove a 
           //PersonGroup entity
           gblPerson.Person.Remove(pg); 

            gblPerson.SaveChanges();
        }
        return true;
    }

Also in this project, all the entities are detached, don’t use proxy types and are designed to move between WCF service boundaries.

도움이 되었습니까?

해결책

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;
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top