【发布时间】:2011-09-28 20:02:03
【问题描述】:
我目前正在使用 AutoMapper 将我的 Entity Framework 实体映射到我的视图模型:
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);
}
}
这很好用。我的问题是何时需要从视图模型转到实体以更新数据库。我应该为此使用 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???
}
【问题讨论】:
-
您的视图模型可以具有实体产品的属性,这样您根本不需要转换。
标签: c# asp.net-mvc entity-framework automapper