是
ASP.NET MVC 4
实体框架5(代码优先方法)
我有常规的控制器和视图。这里的不同之处在于我需要获取实际发送到控制器的属性的名称。这就是我所拥有的:
public ActionResult Update(ClassX data)
{
//do something with data
}
问题在于,当我使用IDbSet.Attach(entity)
时,它不知道哪些属性已被更改,它只是加载从视图发送的属性,它不加载数据库数据并“更新”只是来自观点。
由于发生这种情况,我考虑检查视图发送给控制器的属性,没有运气。如果我能够这样做,我可以更改我的更新方法以加载数据库数据,然后使用新数据进行更新。
有没有人对任何问题有任何建议?
IDbSet.Attach(entity)
感谢。
答案 0 :(得分:1)
[HttpPost]
public ActionResult Update(int id)
{
// Load the entity to be updated from the database
ClassX data = db.ClassXs.SingleOrDefault(x => x.Id == id);
// Modify only the properties that were present in the request
// (BE EXTREMELY CAREFUL WITH THAT -> YOUR CODE IS VULNERABLE TO MASS ASSIGNMENT
// AND THE PROPER SOLUTION IS TO USE A VIEW MODEL WHICH WILL ONLY CONTAIN THE PROPERTIES
// THAT ARE ALLOWED TO BE UPDATED FROM THE VIEW)
this.UpdateModel(data);
// at this stage the data instance will have its properties coming from the view
// updated with fresh values => now you can commit it to the database
...
}