Отсутствует конфигурация карты типов или неподдерживаемое отображение. При попытке присвоить данные объекту DTO - PullRequest
0 голосов
/ 17 февраля 2020

Я использую AutoMapper.Extensions.Microsoft.DependencyInjection. Я использую пакет Automapper NuGet: AutoMapper.Extensions.Microsoft.DependencyInjection (7.0.0) для приложения ASP. NET Core 3.1.

Вот мой объект домена: файл ResourceGroup.cs

public class ResourceGroups
{
    public string id
    {
        get;
        set;
    }

    public int ResourceGroupId
    {
        get;
        set;
    }

    public bool IsPublished
    {
        get;
        set;
    }

    public int? Position
    {
        get;
        set;
    }

    public string CreatedBy
    {
        get;
        set;
    }

    public string CreatedDate
    {
        get;
        set;
    }

    public string UpdatedBy
    {
        get;
        set;
    }

    public string UpdatedDate
    {
        get;
        set;
    }

    public int? ResourceGroupContentId
    {
        get;
        set;
    }

    public int LanguageId
    {
        get;
        set;
    }

    public string GroupName
    {
        get;
        set;
    }
}

Вот мой объект DTO: файл ResourceGroupDTO.cs

public class ResourceGroupDTO
{
    public int ResourceGroupId
    {
        get;
        set;
    }

    public int? Position
    {
        get;
        set;
    }

    [JsonProperty("groupname")]
    [RegularExpression(Constants.GeneralStringRegularExpression)]
    public string GroupName
    {
        get;
        set;
    }
}

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    // Auto Mapper Configurations
    var mappingConfig = new MapperConfiguration(mc =>
    {
        mc.AddProfile(new MappingProfile());
    }

    );
    IMapper mapper = mappingConfig.CreateMapper();
    services.AddSingleton(mapper);
}

MappingProfile.cs

public class MappingProfile : Profile
{
    public MappingProfile()
    {
        CreateMap<ResourceGroups, ResourceGroupDTO>();
        CreateMap<List<ResourceGroups>, List<ResourceGroupDTO>>();
    }
}

file ResourceGroupService.cs

public class ResourceGroupService : IResourceGroupService
{
    private readonly DemoDbContext _dbContext;
    private readonly ICommonService _commonService;
    private readonly IMapper _mapper;
    public ResourceGroupService(DemoDbContext dbContext, ICommonService commonService, IMapper mapper)
    {
        _dbContext = dbContext ?? throw new ArgumentNullException(nameof(dbContext));
        _commonService = commonService ?? throw new ArgumentNullException(nameof(commonService));
        _mapper = mapper ?? throw new ArgumentNullException(nameof(mapper));
    }

    public async Task<ResourceGroupDTO> GetResourceGroupDetailsAsync(int resourceGroupId, int languageId)
    {
        var resourceGroup = await _dbContext.ResourceGroups.Where(rg => rg.ResourceGroupId.Equals(resourceGroupId) && rg.IsPublished.Equals(true))
                                                               .Select(rg => new { rg.ResourceGroupId, rg.Position, rg.GroupName, rg.LanguageId })
                                                               .AsNoTracking().ToListAsync();
        var resGroup = resourceGroup.FirstOrDefault(rg => rg.LanguageId.Equals(languageId));
        return _mapper.Map<ResourceGroupDTO>(resGroup);
    }
}

При отладке вышеуказанного кода я получаю следующую ошибку:

Missing type map configuration or unsupported mapping. \n \nMapping types :  \
n<> f__AnonymousType4 ` 4 ->
ResourceGroupDTO \n<> f__AnonymousType4 ` 4
[
[System.Int32, System.Private.CoreLib, Version =  4.0  .0  .0 , Culture =  neutral, PublicKeyToken =  7  cec85d7bea7798e] , 
[System.Nullable ` 1[
[System.Int32, System.Private.CoreLib, Version =  4.0  .0  .0 , Culture =  neutral, PublicKeyToken =  7  cec85d7bea7798e] ] , 
System.Private.CoreLib , Version =  4.0  .0  .0 ,  Culture =  neutral , PublicKeyToken =  7  cec85d7bea7798e ] , [System.String, System.Private.CoreLib, Version =  4.0  .0  .0 , Culture =  neutral, PublicKeyToken =  7  cec85d7bea7798e] , 
[System.Int32, System.Private.CoreLib, Version =  4.0  .0  .0 , Culture =  neutral, PublicKeyToken =  7  cec85d7bea7798e] ] ->
Author.Query.Persistence.DTO.ResourceGroupDTO \n --  ->AutoMapper.AutoMapperMappingException : Missing type map configuration or unsupported mapping. \n \nMapping types :  \
n<> f__AnonymousType4 ` 4 ->

1 Ответ

1 голос
/ 17 февраля 2020

Вы пытаетесь сопоставить анонимный тип, т.е.

new { rg.ResourceGroupId, rg.Position, rg.GroupName, rg.LanguageId }

, с ResourceGroupDTO, отсюда и ошибка. Чтобы быстро исправить свою ошибку, вы можете просто изменить вышеупомянутое значение на

new ResourceGroupDTO { ResourceGroupId = rg.ResourceGroupId, Position = rg.Position, GroupName = rg.GroupName, LanguageId = rg.LanguageId }

, а затем добавить LanguageId в ResourceGroupDTO и избавиться от маппера.

Но то, что вы действительно должны использовать, это ProjectTo , и вы должны изменить свой .FirstOrDefault на .Where - чтобы сделать ваш запрос более эффективным, в формате, показанном ниже:

await _dbContext.ResourceGroups
.AsNoTracking()
.Where(/* Put your where here */)
.ProjectTo<ResourceGroupDTO>(_mapper.Configuration)
.FirstOrDefaultAsync();

Вы также можете упростить запуск

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...