使用实体框架坚持模型对象
-
20-09-2019 - |
题
我将尽量保持简洁。
我在这里有控制器...
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(CustomObject myCustomObject)
{
...
}
mycustomobject看起来很棒。但是,如果我想使用实体框架保存它,我需要做这样的事情...
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(CustomObject myCustomObject)
{
CustomObject existingObject = repository.GetCustomObject(myCustomObject.ID);
// Set all the attributes of myCustomObject to existingObject
existingObject.SomeMapperFunction(myCustomObject)
repository.Save();
}
有没有办法可以防止进行此映射?
解决方案
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id)
{
CustomObject existingObject = repository.GetCustomObject(id);
TryUpdateModel(existingObject);
// You additionaly can check the ModelState.IsValid here
repository.Save();
}
不隶属于 StackOverflow