【问题标题】:NHibernate, AutoMapper and ASP.NET MVCNHibernate、AutoMapper 和 ASP.NET MVC
【发布时间】:2011-05-04 15:27:24
【问题描述】:

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

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

【问题讨论】:

  • 好吧,想想你的项目,以及你需要实现的所有东西,如果这种方法会给你带来任何问题

标签: nhibernate asp.net-mvc-2 automapper


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    我会将 IMappingEngine 注入控制器,而不是使用静态 Mapper 类。然后,您将获得能够在测试中模拟它的所有好处。

    看看 AutoMapper 的创建者的这个链接,

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-23
      相关资源
      最近更新 更多