簡體   English   中英

Map 帶有 AutoMapper 的新 class 中的兩個獨立對象

[英]Map two separate objects in new class with AutoMapper

我有 2 個模型, ProductsCategories ,這些來自存儲庫上的 model:

IEnumerable<Product> 
IEnumerable<Category>

我創建了一個 WebAPI 並引入了 AutoMapper,最終具有如下代碼,以在它們自己的單獨類中返回產品和類別

public class ProductsController : ApiController
{
....
public IHttpActionResult Get()
    {
        try
        {
            IEnumerable<Product> products = GetProducts();
            var mappedResult = _mapper.Map<IEnumerable<ProductModel>>(products);

            return Ok(mappedResult);
        }
        catch (Exception ex)
        {
            return InternalServerError(ex);
        }
    }

正如我在類別的新 class 中所說的相同代碼。 請注意此 class 的新 model,因此它與域 model ( ProductModel ) 是分開的。

我現在想在我的 MVC 應用程序(不是.Net Core)中創建一個頁面,該頁面需要在下拉列表中顯示類別列表並使用 foreach 循環列出產品。 我創建一個新的 class 如下

Public Class ProductsAndCategoriesModel
{
        public ProductModel Products { get; set; }
        public CategoryModel Categories { get; set; }
}

這里的想法是有一種新方法來加載相同的產品和類別數據,但在它自己的 class 中。 我遵循與上述相同的約定,但我如何使用 AutoMapper map 到這個 class 的兩個不同數據源?

            var mappedResultProducts = _mapper.Map<IEnumerable<ProductsAndCategoriesModel>>(products);
            var mappedResultCategories = _mapper.Map<IEnumerable<ProductsAndCategoriesModel>>(cats);

            //return Ok(mappedResult);

我需要將 map 產品添加到 ProductsAndCategoriesModel 中的 ProductsAndCategoriesModel 和 ProductsAndCategoriesModel 中的 Categories。 我試圖傳遞類別但不能,因為它引發了編譯器異常。 我怎么能做到這一點?

編輯 1

    public ProductCategoryProfile()
    {
        CreateMap<Product, ProductsAndCategoriesModel>();
        CreateMap<Category, ProductsAndCategoriesModel>();
    }

無需使事情變得比應有的復雜。 你為什么不簡單地這樣做:

Model class:

public Class ProductsAndCategoriesModel
{
    public IEnumerable<ProductModel> Products { get; set; }
    public IEnumerable<CategoryModel> Categories { get; set; }
}

映射配置文件:

public ProductCategoryProfile()
{
    CreateMap<Product, ProductModel>();
    CreateMap<Category, CategoryModel>();
}

Controller:

public IHttpActionResult Get()
{
    try
    {
        IEnumerable<Product> products = GetProducts();
        IEnumerable<Category> categories = GetCategories();

        var result = new ProductsAndCategoriesModel
        {
            Products = _mapper.Map<IEnumerable<ProductModel>>(products),
            Categories = _mapper.Map<IEnumerable<CategoryModel>>(categories)
        }

        return Ok(result);
    }
    catch (Exception ex)
    {
        return InternalServerError(ex);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM