c# - 通过操作过滤器属性将实体自动映射到模型?

标签 c# asp.net-mvc-3 automapper

this article , Jimmy Bogard接下来解释了他在进行 MVC 时认可的一些最佳实践。

这篇文章总体来说相当不错,我发现他的建议总体上(在其他博客文章中)非常可靠。不过,他建议使用属性将实体映射到模型。

这怎么样

[AutoMap(typeof(Product), typeof(ShowProduct))]
public ActionResult Details(int id)
{
    var product = _productRepository.GetById(id);
    return View(product);
}

比这更好的(在我看来,这对于这段代码的实际意图来说更具声明性)

public ActionResult Details(int id)
{
    var product = _productRepository.GetById(id);
    var model = Mapper.Map<Product, ShowProduct>(product);
    return View(model);
}

除了这一点之外,似乎在某些情况下这是相当不切实际的,例如操作方法根据输入返回不同的模型,甚至更简单的情况如下:

    [HttpGet]
    public ActionResult Index()
    {
        return List();
    }

    public ActionResult Until(long id) // "id" is the timestamp
    {
        return List(id);
    }

    [NonAction]
    internal ActionResult List(long? timestamp = null, int count = 8)
    {
        IEnumerable<Post> posts = postService.GetLatest(timestamp, count);
        PostListModel model = mapper.Map<IEnumerable<Post>, PostListModel>(posts);
        return ContextView("List", model);
    }

这实际上是一个好的做法,还是只是不合理的,是对本来就很简单的代码的无端混淆?

我问这个问题是出于无知,并不是对我认为很棒的博主进行人身攻击,而且我已经喜欢 AutoMapper 了。

最佳答案

我正在搜索这个主题,并且还浏览了 Los Techies 的帖子。我的下一个搜索导致了这个 Google Groups article在 AutoMapper 用户组中。

看起来吉米已经放弃了这个指导:

Don't use an action filter. We went that route ourselves originally, but eventually settled on custom action results instead. It's a little easier to customize those over action filters, which make it pretty much impossible to supply custom behavior to.

HTH,

Jimmy

关于c# - 通过操作过滤器属性将实体自动映射到模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11838010/

相关文章:

c# - AutoMapper:一对多 -> 多对多

c# - 如何分离未分离的输入C#

c# - .Net Core 中的通用存储库模式与 Entity Framework 的相关性是什么

c# - 是否可以在大括号内使用占位符?

c# - MVC3 中的 "Hooks"

c# - 具有依赖注入(inject)的 AutoMapper 不映射配置文件?

c# - WPF 容器将所有子控件变为只读

c# - 单击 HTML 按钮(不是提交或表单的发布按钮)调用 Controller 的特定操作 Asp.net MVC

JQuery 从多选列表 if 语句获取值 MVC3

c# - Automapper:序列不包含任何元素。