I’m working with EF CTP 4, using POCO models, adding a new object and call SaveChanges() works but updating the object doesn’t work. Here’s the code for update:
public void UpdateContact(Contact contact)
{
var findContact = GetContact(contact.ContactID);
findContact = contact;
_context.SaveChanges();
}
public Contact GetContact(int contactId)
{
return GetAllContacts().SingleOrDefault(c => c.ContactID == contactId);
}
public IQueryable<Contact> GetAllContacts()
{
return _context.Contacts;
}
I’m not sure what I’m doing wrong here. Any idea? Thanks.
The problem is that when you assign
findContact = contacttheEntityStatedoes not get changed in theObjectStateManager(so it’s still set toUnchanged). Therefore, noUpdateSQL statement gets generated for the entity. You have several options to do the update:Option 1: Populate
findContactfield-by-field:Option 2: Use the
ApplyCurrentValuesmethod:Option 3: Attach the updated entity and change the state in the
ObjectStateManager. (Note: this will not make a roundtrip to the database for fetching the existing contact).