views:

635

answers:

1

I asked this question earlier but I think I phrased it incorrectly, so here is attempt number two. I have the following code:

public User EditUser(User userToEdit)
{
    //userToEdit contains values for eagerly loaded contacts entity

    User originalUser = (from u in _entities.UserSet.Include("contacts")
                                 where u.ID == userToEdit.ID
                                 select u).FirstOrDefault();

    _entities.ApplyPropertyChanges(originalUser.EntityKey.EntitySetName, userToEdit);
    _entities.SaveChanges();

    return userToEdit;            
}

Pretty straight forward. However, the contacts entity isn't updated. To my understanding eager loading adds the entity to the data context so when ApplyPropertyChanges is called with the detached userToEdit, the changes to contacts in userToEdit will by applied to the attached contacts entity. What am I missing?

+1  A: 

Yes this is an unfortunate side effect of something called "Independent Associations"

In the EF (at least in 3.5 SP1) relationships are not considered to be part of the Entity, i.e. there are independent.

This means that calling ApplyPropertyChanges(...) only effects the properties that are structurally part of the Entity and not the References.

So you need to change your code to this:

public User EditUser(User userToEdit){    
    //userToEdit contains values for eagerly loaded contacts entity    
    User originalUser = (from u in _entities.UserSet.Include("contacts")                                 
        where u.ID == userToEdit.ID                                 
        select u).FirstOrDefault();  

    _entities.ApplyPropertyChanges(originalUser.EntityKey.EntitySetName, userToEdit);  
    originalUser.Contacts = userToEdit.Contacts;
    _entities.SaveChanges();    
    return userToEdit;            
}

This assumes that userToEdit.Contacts is reference (not a collection), and is not null.

Hope this Helps Alex

PS In .NET 4.0 Beta2 something called FK associations will fix this problem, and make it so your code would work.

Alex James
Thank you very much, that looks like it will do the trick. I'm eagerly awaiting beta 2 of 4.0, most of the headaches I've had with EF look like they're going to be addressed.
Graham