所以我需要一种将 ViewModel 合并到持久性实体中的方法。我可以使用 AutoMapper 执行此操作,还是必须手动执行此操作?
是的,您可以使用 AutoMapper 做到这一点。例如:
public class Model
{
public int Id { get; set; }
public string Name { get; set; }
}
public class ViewModel
{
public string Name { get; set; }
}
class Program
{
static void Main()
{
// define a map (ideally once per appdomain => usually goes in Application_Start)
Mapper.CreateMap<ViewModel, Model>();
// fetch an entity from a db or something
var model = new Model
{
Id = 5,
Name = "foo"
};
// we get that from the view. It contains only a subset of the
// entity properties
var viewModel = new ViewModel
{
Name = "bar"
};
// Now we merge the view model properties into the model
Mapper.Map(viewModel, model);
// at this stage the model.Id stays unchanged because
// there's no Id property in the view model
Console.WriteLine(model.Id);
// and the name has been overwritten
Console.WriteLine(model.Name);
}
}
印刷:
5
bar
并将其转换为典型的 ASP.NET MVC 模式:
[HttpPost]
public ActionResult Update(MyViewModel viewModel)
{
if (!ModelState.IsValid)
{
// validation failed => redisplay view
return View(viewModel);
}
// fetch the domain entity that we want to udpate
DomainModel model = _repository.Get(viewModel.Id);
// now merge the properties
Mapper.Map(viewModel, model);
// update the domain model
_repository.Update(mdoel);
return RedirectToAction("Success");
}