ASP.net MVC - 我应该使用从视图模型AutoMapper实体框架的实体? [英] ASP.net MVC - Should I use AutoMapper from ViewModel to Entity Framework entities?
问题描述
公共ProductsController类:控制器
{
私人IProductRepository productRepository; 公众的ProductsController(IProductRepository productRepository)
{
this.productRepository = productRepository;
} 公众的ActionResult详细信息(INT ID)
{
变种产品= productRepository.GetProduct(ID); 如果(产品== NULL)
返回视图(NOTFOUND); ProductDetailsViewModel模型= Mapper.Map<产品,ProductDetailsViewModel>(产品); 返回查看(模型);
}
}
这工作得很好。我的问题是,当我需要从我的视图模型去我的实体,以更新数据库。我应该使用AutoMapper这个?这是一个坏/危险的做法?
好像AutoMapper有利于扁平化复杂类型为一个简单的(平面)型,但到目前为止,我竭力想从平/简单的去一个更复杂的型像我用的各种导航属性的实体
如果这是一个坏主意,使用AutoMapper要做到这一点,那么我将code是什么样子的创建操作?
公众的ActionResult创建(CreateProductViewModel模型)
{
如果(ModelState.IsValid)
{
//我该怎么办在这里创建我的产品的实体?
}
}
大约一个编辑动作是什么?
公众的ActionResult编辑(INT ID,EditProductViewModel模型)
{
产品产品= productRepository.GetProduct(ID); //如何将我的视图模型转换为我的实体在这一点?
}
我是一个心态的是更新的实体是一个 pretty大不了并没有自动化的工具应该是有史以来使用。手动设置属性。
是其更code,但automapper或数据库实体运行的UpdateModel的一个非常小的量有时可以产生意想不到的后果。更好地确保您的写操作都正确完成。
I am currently using AutoMapper to map my Entity Framework entities to my 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);
}
}
This works well. The question I have is when I need to go from my View Model to my entity in order to update the database. Should I be using AutoMapper for this? Is this a bad/dangerous practice?
It seems like AutoMapper is good for flattening a complex type to a simple (flat) type, but so far I'm struggling trying to go from a flat/simple to a more complex type like my entity with the various navigation properties.
If it is a bad idea to use AutoMapper to do this, then what would my code look like for a Create action?
public ActionResult Create(CreateProductViewModel model)
{
if( ModelState.IsValid )
{
// what do i do here to create my Product entity?
}
}
What about an Edit action?
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???
}
I'm a of the mindset that updating your entities is a pretty big deal and that no automated tool should ever be used. Set the properties manually.
Yes its a very tiny amount of more code but automapper or running updatemodel on database entities can sometimes have unintended consequences. Better to make sure your writes are done correctly.
这篇关于ASP.net MVC - 我应该使用从视图模型AutoMapper实体框架的实体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!