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.
(我一直在探索在ASP.NET MVC3环境中编辑/更新实体框架5中的记录的不同方法,但到目前为止,它们都没有勾选我需要的所有框。)
I'll explain why. (我会解释原因。)
I have found three methods to which I'll mention the pros and cons:
(我找到了三种方法,我将提到它的优点和缺点:)
Method 1 - Load original record, update each property
(方法1 - 加载原始记录,更新每个属性)
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();
}
Pros
(优点)
- Can specify which properties change
(可以指定更改哪些属性)
- Views don't need to contain every property
(视图不需要包含每个属性)
Cons
(缺点)
Method 2 - Load original record, set changed values
(方法2 - 加载原始记录,设置更改的值)
var original = db.Users.Find(updatedUser.UserId);
if (original != null)
{
db.Entry(original).CurrentValues.SetValues(updatedUser);
db.SaveChanges();
}
Pros
(优点)
- Only modified properties are sent to database
(仅将已修改的属性发送到数据库)
Cons
(缺点)
Method 3 - Attach updated record and set state to EntityState.Modified
(方法3 - 附加更新的记录并将状态设置为EntityState.Modified)
db.Users.Attach(updatedUser);
db.Entry(updatedUser).State = EntityState.Modified;
db.SaveChanges();
Pros
(优点)
- 1 x query on database to update
(1 x查询数据库以进行更新)
Cons
(缺点)
- Can't specify which properties change
(无法指定更改哪些属性)
- Views must contain every property
(视图必须包含每个属性)
Question
(题)
My question to you guys;
(我向你们提问;)
is there a clean way that I can achieve this set of goals? (有没有一种干净的方式可以达到这套目标?)
- Can specify which properties change
(可以指定更改哪些属性)
- Views don't need to contain every property (such as password!)
(视图不需要包含每个属性(例如密码!))
- 1 x query on database to update
(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 ;-) (如果不是方法一将占上风;-))
ask by Stokedout translate from so 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…