我已搜索并找到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();
更新对象的最佳方法是什么? 注意:性能对我很重要
答案 0 :(得分:2)
_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
希望它有所帮助!