NHibernate、AutoMapper和ASP.NET MVC

4

我想了解在使用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);
} 

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


好的,考虑一下你的项目以及你需要实现的所有东西,如果这种方法会给你带来任何问题。 - Omu
2个回答

1

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

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通用控制器

编辑: 您可以在此asp.net mvc示例应用程序中查看此技术: http://prodinner.codeplex.com


0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接