实体框架 5 更新记录 [英] Entity Framework 5 Updating a Record
问题描述
我一直在探索在 ASP.NET MVC3 环境中的 Entity Framework 5 中编辑/更新记录的不同方法,但到目前为止,它们都没有满足我的所有需求.我会解释原因.
I have been exploring different methods of editing/updating a record within Entity Framework 5 in an ASP.NET MVC3 environment, but so far none of them tick all of the boxes I need. I'll explain why.
我找到了三种方法,我将提及其优缺点:
I have found three methods to which I'll mention the pros and cons:
方法一 - 加载原始记录,更新每个属性
var original = db.Users.Find(updatedUser.UserId);
if (original != null)
{
original.BusinessEntityId = updatedUser.BusinessEntityId;
original.Email = updatedUser.Email;
original.EmployeeId = updatedUser.EmployeeId;
original.Forename = updatedUser.Forename;
original.Surname = updatedUser.Surname;
original.Telephone = updatedUser.Telephone;
original.Title = updatedUser.Title;
original.Fax = updatedUser.Fax;
original.ASPNetUserId = updatedUser.ASPNetUserId;
db.SaveChanges();
}
优点
- 可以指定更改哪些属性
- 视图不需要包含每个属性
缺点
- 2 x 查询数据库以加载原始数据然后更新它
方法 2 - 加载原始记录,设置更改的值
var original = db.Users.Find(updatedUser.UserId);
if (original != null)
{
db.Entry(original).CurrentValues.SetValues(updatedUser);
db.SaveChanges();
}
优点
- 仅将修改后的属性发送到数据库
缺点
- 视图需要包含所有属性
- 2 x 查询数据库以加载原始数据然后更新它
方法 3 - 将更新的记录和设置状态附加到 EntityState.Modified
db.Users.Attach(updatedUser);
db.Entry(updatedUser).State = EntityState.Modified;
db.SaveChanges();
优点
- 1 x 查询要更新的数据库
缺点
- 无法指定更改哪些属性
- 视图必须包含所有属性
问题
我对你们的问题;有没有一种干净的方法可以实现这组目标?
My question to you guys; is there a clean way that I can achieve this set of goals?
- 可以指定更改哪些属性
- 视图不需要包含所有属性(例如密码!)
- 1 x 查询要更新的数据库
我知道要指出这是一件很小的事情,但我可能缺少一个简单的解决方案.如果不是方法一将占上风;-)
I understand this is quite a minor thing to point out but I may be missing a simple solution to this. If not method one will prevail ;-)
推荐答案
您正在寻找:
db.Users.Attach(updatedUser);
var entry = db.Entry(updatedUser);
entry.Property(e => e.Email).IsModified = true;
// other changed properties
db.SaveChanges();
这篇关于实体框架 5 更新记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!