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

前端 未结 2 1258
無奈伤痛
無奈伤痛 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: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.

提交回复
热议问题