Entity Framework POCO SaveChanges() on Update doesn't work?

眉间皱痕 提交于 2019-12-29 04:47:28

问题


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.


回答1:


The problem is that when you assign findContact = contact the EntityState does not get changed in the ObjectStateManager (so it's still set to Unchanged). Therefore, no Update SQL statement gets generated for the entity. You have several options to do the update:

Option 1: Populate findContact field-by-field:

var findContact = GetContact(contact.ContactID);
findContact.FirstName = contact.FirstName;
findContact.LastName = contact.LastName;
...
_context.SaveChanges();

Option 2: Use the ApplyCurrentValues method:

var findContact = GetContact(contact.ContactID);
_context.ApplyCurrentValues("Contacts", contact);
_context.SaveChanges();

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).

_context.AttachTo("Contacts", contact);
var contactEntry = Context.ObjectStateManager.GetObjectStateEntry(contact);
contactEntry.ChangeState(EntityState.Modified);
_context.SaveChanges();


来源:https://stackoverflow.com/questions/4075107/entity-framework-poco-savechanges-on-update-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!