我搜索并找到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!
更多推荐
发布评论