asp.net-mvclinq-to-sqlmappingviewmodeleditmodel

How should I map Edit Models to Domain Models


I'm trying to understand the best way to map the fields in an Edit Model (posted back from a view form) to a Domain Model so that I can SubmitChanges() and update the database record (via Linq to SQL). My example will be simple and the answer to it is probably to just do it manually. The question I'm asking is for models with many more fields where it could still be done manually and maybe that's the answer - but is there an easier way (using AutoMapper perhaps)?

My Domain Model:

public class Product
{
    public int ProductId { get; set; }
    public string Name { get; set; }
    public int Color { get; set; }
    public string SerialNumber { get; set; }
}

My View/Edit Model:

public class ProductVM
{
    public int ProductId { get; set; }
    public string Name { get; set; }
    public IEnumberable<Color> Colors { get; set; } // To populate a dropdown in the view with color key/values
}

My Controller Action:

[HttpPost]
public ActionResult UpdateProduct(ProductVM product)
{
    var productService = new ProductService();
    productService.Update(product);
}

The Update method in my service layer:

public void Update(ProductVM productVM)
{
    Product product = dataContext.Products.Single(p=>p.ProductId == productVM.ProductId);
    // What's the best way to map the fields of productVM into product so I can submit the changes?
    dataContext.SubmitChanges();
}

I just want to map the fields from productVM that match up with the fields in product. The Edit Model has fields that don't exist in the Domain Model and the Domain Model has fields that don't exist in the Edit Model. My ultimate goal is to update the fields in the database from the fields in the Edit Model.

Thanks


Solution

  • Use Automapper

    public void Update(ProductVM productVM)
    {
        Product product = dataContext.Products.Single(p=>p.ProductId == productVM.ProductId);
        AutoMapper.Mapper.DynamicMap<ProductVM, Product >(productVM, product );
        dataContext.SubmitChanges();
    }