我试图弄清楚如何将域模型一般地映射到表示模型。例如,给定以下简单的对象和接口...
// 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”可以使用反射、基于约定的映射等自动确定映射两个对象的属性以及映射的对象类型。所以,我可以很容易地尝试使用相同的 MapperObject 映射 UserPresentationModel 和 User 等对象。
这可能吗?如果是这样,怎么做?
编辑:为清楚起见,这里是我当前使用的非泛型 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;
}
}
我仍在尝试解决如何使其与 List 一起使用,而不仅仅是单个产品,但这是一个不同的主题 :)