Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
241 views
in Technique[技术] by (71.8m points)

c# - ASP.net MVC - Should I use AutoMapper from ViewModel to Entity Framework entities?

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???
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...