gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 22:26:25 25 4
gpt4 key购买 nike

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-users 组中。

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

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# - 通过 Action 过滤器属性将实体自动映射到模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11838010/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com