我目前正在使用AutoMapper将我的Entity Framework实体映射到我的View Model:
public class ProductsController : Controller
{
private IProductRepository productRepository;
public ProductsController(IProductRepository productRepository)
{
this.productRepository = productRepository;
}
public ActionResult Details(int id)
{
var product = productRepository.GetProduct(id);
if( product == null )
return View("NotFound");
ProductDetailsViewModel model = Mapper.Map<Product, ProductDetailsViewModel>(product);
return View(model);
}
}
这很好用 . 我的问题是当我需要从我的View Model转到我的实体以更新数据库时 . 我应该使用AutoMapper吗?这是一个糟糕/危险的做法吗?
似乎AutoMapper很适合将复杂类型展平为简单(平面)类型,但到目前为止,我正在努力尝试从平面/简单到更复杂的类型,如我的实体具有各种导航属性 .
如果使用AutoMapper执行此操作是个坏主意,那么我的代码对于Create操作会是什么样子?
public ActionResult Create(CreateProductViewModel model)
{
if( ModelState.IsValid )
{
// what do i do here to create my Product entity?
}
}
编辑动作怎么样?
public ActionResult Edit(int id, EditProductViewModel model)
{
Product product = productRepository.GetProduct(id);
// how do i convert my view model to my entity at this point???
}
4 回答
我是一个更新你的实体的心态是 pretty big deal 并且不应该使用任何自动化工具 . 手动设置属性 .
是的,它只是一小部分代码,但是自动化或在数据库实体上运行updatemodel有时会产生意想不到的后果 . 最好确保您的写入正确完成 .
我使用AutoMapper和一个专门的映射类,它可以理解如何从一个简单的模型中创建一个复杂的模型 . AutoMapper用于处理类中的一对一映射和自定义逻辑,以执行更复杂的操作(如关系等) . 所有AutoMapper配置都在映射类的静态构造函数中完成,该构造函数还验证映射配置,以便错误提前失败 .
您还可以尝试将AutoMapper配置为仅映射标量属性(而不是必须
.Ignore()
您不希望它的每个属性(包括继承的属性,如.EntityKey
和.EntityState
) .更多信息,请致电http://www.prosoftnearshore.com/blog/post/2012/03/14/Using-AutoMapper-to-update-Entity-Framework-properties.aspx
基本上自动化很糟糕,我写了一篇博客文章http://blog.gavryli.uk/2015/12/02/why-automapping-is-bad-for-you/