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

前端 未结 2 1253
無奈伤痛
無奈伤痛 2020-12-18 16:31

I have not really a \"problem\" but I found the way I develop this code not really well.

I have my countries controller (Edit method) (WebUI layer):

         


        
相关标签:
2条回答
  • 2020-12-18 17:17

    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;
        } 
    
    0 讨论(0)
  • 2020-12-18 17:27

    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.

    0 讨论(0)
提交回复
热议问题