代码之家  ›  专栏  ›  技术社区  ›  mathieu

NHibernate、automapper和ASP.NET MVC

  •  4
  • mathieu  · 技术社区  · 14 年前

    我想知道使用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);
    } 
    

    这是正确的,还是可以改进?

    2 回复  |  直到 14 年前
        1
  •  1
  •   Community CDub    8 年前

    我在一个项目中就是这样做的:

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

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

    你把你的映射代码放在前两个方法中(不管映射技术如何,你甚至可以手工完成) 当您得到modelstate.isvalid==false时,rebuildInput是用于的,只需再次调用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

        2
  •  0
  •   Castrohenge    14 年前

    我将把imappingengine注入控制器,而不是使用静态映射器类。然后,您就可以在测试中模拟这一点了。

    看看automapper的创建者的链接,

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