2011-08-05 110 views
1

我想要了解将编辑模型中的字段(从视图窗体回发)映射到域模型的最佳方式,以便我可以SubmitChanges()并更新数据库记录(通过Linq to SQL)。我的例子很简单,答案可能是手动完成。我问的问题是模型有更多的领域,它仍然可以手动完成,也许这就是答案 - 但有没有更简单的方法(使用AutoMapper也许)?我应该如何将编辑模型映射到域模型

我的域模型:

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

我查看/编辑型号:

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 
} 

我的控制器操作:

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

在我的业务层的更新方法:

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(); 
} 

我只想映射productVM中与字段匹配的字段。编辑模型具有域模型中不存在的字段,并且域模型具有编辑模型中不存在的字段。我的最终目标是从编辑模型中的字段更新数据库中的字段。

感谢

回答

2

使用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(); 
} 
+0

完美的 - 它映射正是我想要的字段。谢谢。 – BKahuna

相关问题