Jeremy
Jeremy

Reputation: 147

Entity Framework saving child

I'm new to EF and I'm having a little bit of trouble with my children. I can save an instance of an entity object just fine but when I try to save children associated with that entity, it blows up on me. enter image description here

The model I'm currently working with.

    public bool UpdateSelectedUser(user selectedUser)
    {
        nsdc_supplyEntities ctx = new nsdc_supplyEntities();

        try
        {
            user editUser = ctx.users
                .Include(ug => ug.network_group)
                .Where(u => u.id == selectedUser.id).FirstOrDefault();

            editUser.full_name = selectedUser.full_name;
            editUser.office_phone = selectedUser.office_phone;
            editUser.cell_phone = selectedUser.cell_phone;
            editUser.home_phone = selectedUser.home_phone;
            editUser.text_address = selectedUser.text_address;
            editUser.email = selectedUser.email;

            foreach (network_group group in selectedUser.network_group)
            {
                editUser.network_group.Add(group);
            }

            ctx.SaveChanges();
        }
        catch (Exception e)
        {
        }
    }

The code I'm using. It errors on the editUser.network_group.Add(group); line saying "The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects". I've done a little digging into potential answers on google and SO but so far haven't found anything that solves the problem.

-UPDATE- Changed the group foreach to reflect Shyju's suggestion. It got me farther along but exposed another problem:

            foreach (network_group group in selectedUser.network_group)
            {
                var groupEntity = new network_group 
                { 
                    id = group.id,
                    full_name = group.full_name,
                    distribution_list_email = group.distribution_list_email
                };
                if (editUser.network_group.Where(g => g.id == groupEntity.id).Count() < 1)
                {
                    editUser.network_group.Add(groupEntity);
                }
            }

There's a unique constraint which threw an error. I noticed I was inserting some duplicate entries. So now if the user already has a the group, it doesn't add it. However now that I'm adding only groups that are not currently associated with the user, I'm still getting a unique constraint error. What I found is, it now adds a new group to the groups table and then associates it with the user. I want to add an existing group to the user, not create a new group. Getting closer! :)

Upvotes: 1

Views: 1991

Answers (3)

Gert Arnold
Gert Arnold

Reputation: 109109

The easiest approach is to make sure that selectedUser (and therefore its network_group) is not attached to the context it currently belongs to. Then the groups can be added to the new editUser as in your original code.

Upvotes: 0

McAden
McAden

Reputation: 13972

The original error is happening because you're adding entities that have already been created in a different context to an entity in a context you just created.

// Get the ids
var userGroupIds = selectedUser.network_groups.Select(e => e.id);

// Use the ids to retrieve their equivalent entities from the new context
var userGroups = ctx.network_groups.Where(e => userGroupIds.Contains(e.id));

// Add the groups from the correct context.
foreach (network_group group in userGroups)
{
    editUser.network_group.Add(group);
}

Upvotes: 1

Shyju
Shyju

Reputation: 218732

I guess this may fix the problem. Create new network_group1 object and set the property values and add that to the collection.

foreach (network_group group in selectedUser.network_group)
{
   var groupEntity=new network_group { id=group.id,full_name=group.ful_lname
                         ,distribution_list_email=group.distribution_list_email};
   editUser.network_group.Add(groupEntity);
}
ctx.SaveChanges();

Upvotes: 1

Related Questions