簡體   English   中英

映射兩個相同的模型,嵌套有 automapper

[英]Map two identical models, nested with automapper

我做了一些研究,但我找不到我想要的。

我有一個無窮無盡的菜單。 我有一個 MenuDTO 和一個 MenuViewModel 用於此菜單。 我在模型和 DTO 之間匹配沒有問題,但是在將 DTO 映射到 ViewModel 時遇到問題。 顯然我找不到解決方案,你能幫忙嗎?

我的 MenuDTO 對象

    public class MenuDto : BaseDto
    {
        public string Name { get; set; }
        public string Icon { get; set; }
        public string Order { get; set; }
        public string Url { get; set; }
        public bool IsVisible { get; set; }
        public int ParentId { get; set; }
        public MenuDto ParentMenu { get; set; }
        public List<MenuDto> Menus { get; set; }
    }

和 MenuViewModel

    public class MenuViewModel
    {
        public int Id { get; set; }        
        public bool IsActive { get; set; }
        public string Name { get; set; }
        public string Icon { get; set; }
        public string Order { get; set; }
        public string Url { get; set; }
        public bool IsVisible { get; set; }
        public int ParentId { get; set; }
        public MenuViewModel ParentMenu { get; set; }
        public List<MenuViewModel> Menus { get; set; }
    }

這就是我映射 MenuDTO 和 MenuViewModel 對象的方式。

    public class WebProfile : Profile
    {
        public WebProfile()
        {
            CreateMap<MenuDto, MenuViewModel>();
            CreateMap<MenuViewModel, MenuDto>();
        }
    }

我在控制器中這樣調用

var navMenuItems = _mapper.Map<List<MenuViewModel>(_menuService.GetNavMenus());

盡管所有字段都已映射,但我在“菜單”字段上收到錯誤消息。

我得到的錯誤信息是;

AutoMapperMappingException: Missing type map configuration or unsupported mapping.

Mapping types:
MenuDto -> MenuViewModel
BiPortal2020.Business.ServiceDTOs.Menu.MenuDto -> BiPortal2020.WebUI.Areas.Admin.Models.Menu.MenuViewModel
lambda_method(Closure , MenuDto , MenuViewModel , ResolutionContext )

AutoMapperMappingException: Error mapping types.

Mapping types:
Object -> List`1
System.Object -> System.Collections.Generic.List`1

錯誤消息暗示 - AutoMapper 無法在MenuDtoMenuViewModel之間進行MenuDto ,或者無法找到定義的映射。

我已經測試了您的映射,它們完全沒問題。 因此,剩下的可能性是 AutoMapper 無法找到您的映射。

我假設您在評論部分提到的Business LayerUI Layer是兩個獨立的項目。 由於WebProfile是在UI Layer定義的,因此您必須告訴 AutoMapper 它應該搜索該程序集以查找映射。 由於您的模型和 DTO 之間的映射正在工作,我猜您已經為BusinessProfile中定義的Business Layer做了同樣的工作。

我不知道你現有的代碼,但你可以做這樣的事情 - 在Startup.Configure方法中添加/修改以下行 -

services.AddAutoMapper(typeof(IDtoMapping), typeof(IViewModelMapping));

其中IDtoMappingIViewModelMapping是分別在Business LayerUI Layer中聲明的兩個標記接口(空接口,僅用於標識它們所在的程序集)。

暫無
暫無

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

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