EF Update using EntityState.Modified

前端 未结 3 1964
一个人的身影
一个人的身影 2021-02-08 05:40

Usually I\'m using this code

Member member = ctx.Members.Find(id);
member.Name = txtName.Text;
ctx.Entry(member).State = EntityState.Modified;
ctx.SaveChanges();         


        
相关标签:
3条回答
  • 2021-02-08 06:13

    Like the other guys have mentioned your context tracks the changes to the object automatically.

    I find it more useful for instance when I use return json to a mvc controller where the original object loses change tracking when first converted to json for the view. In that case I have to specifically set the objects entity state before saving changes.

    0 讨论(0)
  • 2021-02-08 06:19

    The EntityState.Modified is useless in your case because the entity your are updating is already tracked by the context as you retrieve it from the context.

    You would need it in the following scenario where you don't retrieve your entity from the context :

    Member member = new Member({Id=1, Name="member"}) ;
    context.Entry(member).State = EntityState.Modified; 
    context.SaveChanges();
    

    Also, as specified in previous answer, your context sometimes tracks only a limited "view" of the database and therefore you need to init the tracking manually like above.

    Microsoft doc

    0 讨论(0)
  • 2021-02-08 06:32

    If you are using change tracking then proxy objects listen to properties changes and update context automatically which is quite useful in mvvm where you just bind properties to controls and don't have to write code behind to update context

    If you are not using change tracking (for example when you are dealing with large amount of entities) you have to update context yourself

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