2011-08-13 54 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