是否有意义创建一个对象,该对象仅包含用户将在网页上输入的属性,在控制器中使用它进行绑定,然后映射到完整的实体对象?或者您应该只使用实体对象,并使用Include和Exclude来限制输入绑定的内容?
我已经开始喜欢使用接口来隔离更新对象时应包含哪些属性.
例如:
要创建和更新人物对象:
interface ICreatePerson
{
string Name { get; set; }
string Sex { get; set; }
int Age { get; set; }
}
interface IUpdatePerson
{
string Name { get; set; }
}
class Person : ICreatePerson, IUpdatePerson
{
public int Id { get; }
public string Name { get; set; }
public string Sex { get; set; }
public int Age { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
然后,在绑定模型时,只需使用适当的接口作为类型,它只会更新name属性.
这是一个示例控制器方法:
public ActionResult Edit(int id, FormCollection collection)
{
// Get orig person from db
var person = this.personService.Get(id);
try
{
// Update person from web form
UpdateModel<IUpdatePerson>(person);
// Save person to db
this.personService.Update(person);
return RedirectToAction("Index");
}
catch
{
ModelState.AddModelErrors((person.GetRuleViolations());
return View(person);
}
}
Run Code Online (Sandbox Code Playgroud)
请参阅此文章(和评论),以便对选项进行非常好的讨论.
| 归档时间: |
|
| 查看次数: |
2172 次 |
| 最近记录: |