2011-08-13 49 views
0

我想弄清楚如何一般地将领域模型映射到演示模型。例如,假设下面的简单对象和接口...如何一般地将领域模型映射到演示模型?

// Product 
public class Product : IProduct 
{ 
    public int ProductID { get; set; } 
    public string ProductName { get; set; } 
} 

public interface IProduct 
{ 
    int ProductID { get; set; } 
    string ProductName { get; set; } 
} 

// ProductPresentationModel 
public class ProductPresentationModel : IProductPresentationModel 
{ 
    public int ProductID { get; set; } 
    public string ProductName { get; set; } 
    public bool DisplayOrHide { get; set; } 
} 

public interface IProductPresentationModel 
{ 
    int ProductID { get; set; } 
    string ProductName { get; set; } 
    bool DisplayOrHide { get; set; } 
} 

我希望能够写这样的代码......

MapperObject mapper = new MapperObject(); 
ProductService service = new ProductService(); 
ProductPresentationModel model = mapper.Map(service.GetProductByID(productID)); 

...其中“MapperObject”可以自动找出哪些属性映射到两个对象之间,以及使用反射,基于约定的映射等映射哪些对象。因此,我可以轻松地尝试映射像UserPresentationModel和User一样的对象MapperObject。

这可能吗?如果是这样,怎么样?

编辑:只是为了清楚起见,这里是我目前使用非通用MapperObject的例子:

public class ProductMapper 
{ 
    public ProductPresentationModel Map(Product product) 
    { 
     var presentationModel = new ProductPresentationModel(new ProductModel()) 
           { 
            ProductID = product.ProductID, 
            ProductName = product.ProductName, 
            ProductDescription = product.ProductDescription, 
            PricePerMonth = product.PricePerMonth, 
            ProductCategory = product.ProductCategory, 
            ProductImagePath = product.ProductImagePath, 
            ProductActive = product.ProductActive 
           }; 

     return presentationModel; 
    } 
} 

我仍然试图找出如何得到这个与名单的工作,而不是只是一个产品,但这是一个不同的话题:)

回答

1

我看到你想要的。您希望将您的域实体(Product)映射到某种类型的DTO对象(ProductPresentationModel),以便与您的客户(GUI,外部服务等)进行通信。

我有你想要的所有功能打包到AutoMapper框架中。

你可以用AutoMapper这样写: Mapper.CreateMap();

看看这个维基https://github.com/AutoMapper/AutoMapper/wiki/Flattening

好运。 /致电Magnus