2010-08-21 86 views
4

我想知道使用NHibernate,AutoMapper和ASP.NET MVC的“最佳实践”。目前,我使用的: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)); 

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

这是正确的,还是可以提高?

+0

好吧,想想你的项目,以及所有t他的东西,你将需要实施,如果这种方法会造成你的任何问题 – Omu 2010-08-23 05:43:43

回答

1

是如何我在一个项目在做'S:

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

实现这个接口为每个实体或/和一些一组实体可以做一个通用的实体并在每个控制器中使用它;使用IoC;

你把你的映射代码放在前2个方法中(无需考虑映射技术,你甚至可以手工完成) 和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

编辑: 你可以看到在这个技术一个asp.net mvc示例应用程序在这里: http://prodinner.codeplex.com