我想知道一个使用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);
} 这是正确的,还是可以改进的?
发布于 2010-08-23 21:03:01
这就是我在一个项目中所做的:
public interface IBuilder<TEntity, TInput>
{
TInput BuildInput(TEntity entity);
TEntity BuildEntity(TInput input);
TInput RebuildInput(TInput input);
}为每个实体或/和某些实体组实现此接口,您可以创建一个通用接口并在每个控制器中使用它;使用IoC;
您将映射代码放在前两个方法中(与映射技术无关,您甚至可以手动完成),RebuildInput用于当您获得ModelState.IsValid == false时,只需再次调用BuildEntity和BuildInput即可。
以及在控制器中的用法:
public ActionResult Create()
{
return View(builder.BuildInput(new TEntity()));
}
[HttpPost]
public ActionResult Create(TInput o)
{
if (!ModelState.IsValid)
return View(builder.RebuildInput(o));
repo.Insert(builder.BuilEntity(o));
return RedirectToAction("index");
}实际上,我有时会使用泛型控制器,它用于更多的实体,比如:asp.net mvc generic controller
EDIT:您可以在下面的asp.net mvc示例应用程序中看到这种技术:http://prodinner.codeplex.com
发布于 2010-08-23 19:44:33
我将把IMappingEngine注入到控制器中,而不是使用静态的Mapper类。然后,您将获得能够在测试中模拟它的所有好处。
看看AutoMapper的创建者提供的链接,
http://www.lostechies.com/blogs/jimmy_bogard/archive/2009/05/11/automapper-and-ioc.aspx
https://stackoverflow.com/questions/3538706
复制相似问题