【问题标题】:How to generically map a domain model to a presentation model?如何一般地将域模型映射到表示模型?
【发布时间】:2011-08-13 19:26:20
【问题描述】:

我试图弄清楚如何将域模型一般映射到表示模型。例如,给定以下简单的对象和接口...

// 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 一起工作,而不仅仅是一个产品,但这是一个不同的话题 :)

【问题讨论】:

    标签: mapping domain-model presentation-model


    【解决方案1】:

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

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

    你可以用 AutoMapper 写成这样: 映射器.CreateMap();

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-17
      • 2015-11-12
      • 1970-01-01
      • 2011-07-03
      • 1970-01-01
      • 2011-07-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多