在 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/