我想弄清楚如何一般地将领域模型映射到演示模型。例如,假设下面的简单对象和接口...如何一般地将领域模型映射到演示模型?
// 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;
}
}
我仍然试图找出如何得到这个与名单的工作,而不是只是一个产品,但这是一个不同的话题:)