这是在EF6中更新对象的好方法(Which is the good way to update object in EF6)

编程入门 行业动态 更新时间:2024-10-28 10:30:42
这是在EF6中更新对象的好方法(Which is the good way to update object in EF6)

我搜索并找到2种方法来更新EF中的对象

var attachedEntity = _context.EntityClasses.Local.First(t => t.Id == entity.Id); //We have it in the context, need to update. if (attachedEntity != null) { var attachedEntry = _context.Entry(attachedEntity); attachedEntry.CurrentValues.SetValues(entity); } else { ////If it's not found locally, we can attach it by setting state to modified. ////This would result in a SQL update statement for all fields ////when SaveChanges is called. var entry = _context.Entry(entity); entry.State = EntityState.Modified; } _context.SaveChanges();

而其他方式似乎更容易

var entity = _context.EntityClasses.FirstOrDefault(t => t.Id == entity.Id); _context.Entry(entity ).EntityState.Modified _context.SaveChanges();

更新对象的最佳方法是什么? 注意:性能对我很重要

I have searched and find 2 way to update object in EF

var attachedEntity = _context.EntityClasses.Local.First(t => t.Id == entity.Id); //We have it in the context, need to update. if (attachedEntity != null) { var attachedEntry = _context.Entry(attachedEntity); attachedEntry.CurrentValues.SetValues(entity); } else { ////If it's not found locally, we can attach it by setting state to modified. ////This would result in a SQL update statement for all fields ////when SaveChanges is called. var entry = _context.Entry(entity); entry.State = EntityState.Modified; } _context.SaveChanges();

And other way is seem more easy

var entity = _context.EntityClasses.FirstOrDefault(t => t.Id == entity.Id); _context.Entry(entity ).EntityState.Modified _context.SaveChanges();

What is best way to update object? NOTE: the performence is importance with me

最满意答案

_context.EntityClasses.Local.First(t => t.Id == entity.Id)=>表示您要仔细检查本地实体(来自DB的最新加载),并且不会发送到DB以查找记录所以性能更快。

_context.EntityClasses.FirstOrDefault(t => t.Id == entity.Id):此命令在DB中查找实体。 这意味着EF创建查询并在DB中查找。

以下链接是Entity.Local.Find和Entity.Find之间的区别。查找http://msdn.microsoft.com/en-us/data/jj592872.aspx

希望能帮助到你!

_context.EntityClasses.Local.First(t => t.Id == entity.Id) => means that you want to double check the entity on local (the latest loading from DB) and it is not send to DB to find the record so the performance is faster.

_context.EntityClasses.FirstOrDefault(t => t.Id == entity.Id): This command is look up the entity in DB. That means EF creates the query and look up in DB.

The below link is the difference of between Entity.Local.Find & Entity.Find http://msdn.microsoft.com/en-us/data/jj592872.aspx

Hope it helps!

更多推荐

本文发布于:2023-07-15 15:28:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1115353.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:这是   对象   方法   object   good

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!