NHibernate, AutoMapper, and ASP.NET MVC

I'm curious about the "best practice" using NHibernate, AutoMapper, and ASP.NET MVC. I am currently using:

class Entity { public int Id { get; set; } public string Label { get; set; } } class Model { public int Id { get; set; } public string Label { get; set; } } 

The entity and model are displayed as follows:

 Mapper.CreateMap<Entity,Model>(); Mapper.CreateMap<Model,Entity>() .ConstructUsing( m => m.Id == 0 ? new Entity() : Repository.Get( m.Id ) ); 

And in the controller:

 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); } 

Is this right or can it be improved?

+4
source share
2 answers

what i did in the project:

 public interface IBuilder<TEntity, TInput> { TInput BuildInput(TEntity entity); TEntity BuildEntity(TInput input); TInput RebuildInput(TInput input); } 

implement this interface for each object or /, and for some group of entities you can make a general one and use it in each controller; use IoC;

you put your mapping code in the first 2 methods (no matter what display technology you can even do it manually) and RebuildInput is when you get the ModelState.IsValid == false value, just call BuildEntity and BuildInput again.

and use in the controller:

  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"); } 

I really sometimes use a common controller, which is used for more objects like here: asp.net mvc general controller

EDIT: you can see this technique in the asp.net mvc example application here: http://prodinner.codeplex.com

+1
source

I would inject IMappingEngine into the controller instead of using the static Mapper class. Then you get all the benefits of being able to mock it in your tests.

Take a look at this link with the creator of AutoMapper,

http://www.lostechies.com/blogs/jimmy_bogard/archive/2009/05/11/automapper-and-ioc.aspx

0
source

All Articles