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」は、2つのオブジェクト間でどのプロパティがマップされ、どのような種類のオブジェクトがマッピングされているかを、リフレクションや規則ベースのマッピングなどを使用して自動的に把握できます。したがって、同じように簡単に試すことができます。 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;
    }
}

私はまだこれを単一の製品ではなくリストで機能させる方法を模索していますが、それは別のトピックです:)

4

1 に答える 1

1

私はあなたが欲しいと思います。ドメインエンティティ(Product)をある種のDTOオブジェクト(ProductPresentationModel)にマップして、クライアント(GUI、外部サービスなど)と通信する必要があります。

私はあなたが探しているこのすべての機能をAutoMapperフレームワークに詰め込んでいます。

AutoMapperを使用すると、次のように記述できます。Mapper.CreateMap();

このウィキを見てくださいhttps://github.com/AutoMapper/AutoMapper/wiki/Flattening

幸運を。/よろしくマグナス

于 2011-09-20T05:56:54.937 に答える