在我看来,您确实需要使用 2 个单独的“模型”——您的 ViewModel,它是您的 MVC 项目中的内容,并呈现到您的视图中。以及业务逻辑层中的第二个实体模型。这是标准的“企业”编程设计。它使您可以更好地控制数据。这个想法是这样的。
UI 组装(MVC 项目)
ViewModel 定义
public class MyModel {
public int ID { get; set; }
.... // bunch of other properties
}
控制器
public class InterestingController : Controller {
public ActionResult CreateNewWidget() {
var model = new MyModel();
return View(model);
}
[HttpPost]
public ActionResult CreateNewWidget(MyModel model) {
if(ModelState.IsValid) {
// your ctor can define the order of your properties being sent in and you can set the entity values in the ctor body however you choose to. Note never SET an ID/Primary key on a Create, let the DB handle that. If you need to return the new Key value, get it from the insert proc method in your DAL and return it up the stack
var entityModel = new EntityFromBLL(model.Name, model.OtherProperty, ... etc);
entityModel.Save(User.Identity.Name); // your save method should always capture WHO is doing the action
}
return View(model);
}
public ActionResult UpdateExistingWidget(int id) {
var entityModel = new EntityFromBLL(id); // get the existing entity from the DB
var model = new MyModel(entityModel.ID, entityModel.Name, ... etc); // populate your ViewModel with your EntityModel data in the ViewModel ctor - note remember to also create a parameterless default ctor in your ViewModel as well anytime you create a ctor in a ViewModel that accepts parameters
return View(model);
}
[HttpPost]
public ActionResult UpdateExistingWidget(MyModel model) {
if(ModelState.IsValid) {
var entityModel = new EntityFromBLL(model.ID); // always pull back your original data from the DB, in case you deal with concurrency issues
// now go thru and update the EntityModel with your new ViewModel data
entityModel.Name = model.Name;
//... etc set all the rest of the properties
// then call the save
entityModel.Save(User.Identity.Name);
}
return View(model)
}
}
您的实体模型应该使用私有字段、公共属性、一个接受插入的所有必需字段(减去主键)的 ctor、一个接受主键然后可以静态调用内部加载方法以返回的 ctor 来定义一个填充的对象。业务规则和属性验证以及单个 Save 方法。Save 方法应在设置所有属性后检查 IsDirty 位并调用相应的 Insert 或 Update 方法 .. 这又应调用 DAL 传递 DTO