我正试图找出如何将域模型一般地映射到表示模型。例如,给定以下简单的对象和接口…
// 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;
}
}
我仍然在努力找出如何让这个工作与列表,而不仅仅是一个单一的产品,但这是一个不同的主题:)
我看到你想要的。你想要将你的域实体(Product)映射到某种DTO对象(ProductPresentationModel),以便与你的客户端(GUI,外部服务等)通信。
如果你有所有这些功能,你正在寻找打包到AutoMapper框架。
你可以用AutoMapper这样写:
Mapper.CreateMap ();看看这个wiki https://github.com/AutoMapper/AutoMapper/wiki/Flattening
好运。