Is there a better way to update my entities with the Entity framework?

杀马特。学长 韩版系。学妹 提交于 2019-11-29 08:48:22

Generally you can update your object without loading it from DB but you have to know its Id.

Your update function can look like:

public void UpdateCountry(Country country)     
{         
  EnsureValidForUpdate(country); 
  _objectContext.Attach(country);

  ObjectStateEntry entry = _objectContext.ObjectStateManager.GetObjectStateEntry(country);
  entry.SetModifiedProperty("Name");
  entry.SetModifiedProperty("ISOCode");

  _objectContext.SaveChanges();    
} 

I didn't use your repository and instead I used ObjectContext instance. This code requires that your Country instance has set Id, Name and ISOCode. The update will be done only on Name and ISOCode fields.

But I have to mention that I'm not using this way. Loading entity first is much better approach in EF when you start to work with complex entities and relations.

You can call this method in a loop. Then after the loop call context.SaveChanges();

    public void UpdateCountry(Item updateItem)     
    {         
        context.YourDbObjects.Attach(updateItem);

        DbEntityEntry<Item> entry = context.Entry(updateItem);

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