我想了解在使用NHibernate、AutoMapper和ASP.NET MVC时的最佳实践。目前,我的做法是:
class Entity
{
public int Id { get; set; }
public string Label { get; set; }
}
class Model
{
public int Id { get; set; }
public string Label { get; set; }
}
实体和模型的映射如下所示:
Mapper.CreateMap<Entity,Model>();
Mapper.CreateMap<Model,Entity>()
.ConstructUsing( m => m.Id == 0 ? new Entity() : Repository.Get( m.Id ) );
在控制器中:
public ActionResult Update( Model mdl )
{
// IMappingEngine is injected into the controller
var entity = this.mappingEngine.Map<Model,Entity>( mdl );
Repository.Save( entity );
return View(mdl);
}
这是正确的吗,还可以改进吗?