使用EntityState.Modified的EF更新 [英] EF Update using EntityState.Modified

查看:113
本文介绍了使用EntityState.Modified的EF更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常我正在使用此代码

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

我在 SO 上找到了一个不使用 EntityState.Modified 来更新模型。我尝试删除该行,但该行仍然有效。使用 EntityState.Modified 而不使用 EntityState.Modified 的优缺点是什么?

when I want to update the model using entity framework. I found an example on SO that doesn't use EntityState.Modified to update the model. I try to remove the line and it's still working. What is the pros and cons use EntityState.Modified and doesn't use EntityState.Modified?

注意:我在WinForms中首先使用Entity Framework 6代码

Notes: I'm using Entity Framework 6 Code First in WinForms

推荐答案

EntityState .Modified在您的情况下是无用的,因为当您从上下文中检索要更新的实体时,上下文已经对其进行了跟踪。

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文档

这篇关于使用EntityState.Modified的EF更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆