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”可以使用反射、基于约定的映射等自动确定映射两个对象的属性以及映射的对象类型。所以,我可以很容易地尝试使用相同的 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 一起使用,而不仅仅是单个产品,但这是一个不同的主题 :)

4

1 回答 1

1

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

我将您正在寻找的所有这些功能都打包到 AutoMapper 框架中。

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

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

祝你好运。/最好的问候马格努斯

于 2011-09-20T05:56:54.937 回答