简体   繁体   English

ASP.Net Core 中的 AutoMapper 问题

[英]An issue with AutoMapper in ASP.Net Core

I have 2 classes to map:我有 2 个班级到 map:

public class Note
    {
        public Guid UserId { get; set; }
        public Guid Id { get; set; }
        public string Title { get; set; }
        public string Body { get; set; }
        public DateTime CreationDate { get; set; }
        public DateTime EditDate { get; set; }
    }
public class NoteDetailsVm : IMapWith<Note>
    {
        public Guid Id { get; set; }
        public string Title { get; set; }
        public string Body { get; set; }
        public DateTime CreationDate { get; set; }
        public DateTime EditDate { get; set; }

        public void Mapping(Profile profile)
        {
            profile.CreateMap<Note, NoteDetailsVm>();
        }
    }

Here is the mapping profile and the mapping interface:这是映射配置文件和映射界面:

public class AssemblyMappingProfile : Profile
    {
        public AssemblyMappingProfile(Assembly assembly) =>
            ApplyMappingsFromAssembly(assembly);

        private void ApplyMappingsFromAssembly(Assembly assembly)
        {
            var types = (from t in assembly.GetExportedTypes()
                        where t.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IMapWith<>))  
                        select t).ToList();

            foreach (var type in types)
            {
                var instance = Activator.CreateInstance(type);
                var methodInfo = type.GetMethod("Mapping");
                methodInfo?.Invoke(instance, new object[] { this });
            }
        }
    }
public interface IMapWith<T>
    {
        void Mapping(Profile profile) =>
            profile.CreateMap(typeof(T), GetType());
    }

I use this method to handle requests and get the viewmodel:我使用此方法处理请求并获取视图模型:

public async Task<NoteDetailsVm> Handle(GetNoteDetailsQuery request, CancellationToken cancellationToken)
        {
            var entity = await _dbContext.Notes.FirstOrDefaultAsync(note => note.Id == request.Id, cancellationToken);

            if (entity == null || entity.UserId != request.UserId)
            {
                throw new NotFoundException(nameof(Note), request.Id);
            }

            return _mapper.Map<NoteDetailsVm>(entity);
        }

So when I run the tests, I get such error though I have the necessary mappings:因此,当我运行测试时,尽管我有必要的映射,但还是出现了这样的错误:

AutoMapper.AutoMapperMappingException: Missing type map configuration or unsupported mapping.

AutoMapper.AutoMapperMappingException
Missing type map configuration or unsupported mapping.

Mapping types:
Note -> NoteDetailsVm
Notes.Domain.Note -> Notes.Application.Notes.Queries.GetNoteDetails.NoteDetailsVm
   at lambda_method259(Closure , Object , NoteDetailsVm , ResolutionContext )
   at Notes.Application.Notes.Queries.GetNoteDetails.GetNoteDetailsQueryHandler.Handle(GetNoteDetailsQuery request, CancellationToken cancellationToken)

Why isn't the mapping working and how can I fix this?为什么映射不起作用,我该如何解决?

You most probably don't handle initialization in your tests.您很可能不会在测试中处理初始化。 Check this guide here: https://www.thecodebuzz.com/unit-test-mock-automapper-asp.net-core-imapper/在此处查看本指南: https://www.thecodebuzz.com/unit-test-mock-automapper-asp.net-core-imapper/

The essence of it are these lines of code:它的本质是这些代码行:

            if (_mapper == null)
            {
                var mappingConfig = new MapperConfiguration(mc =>
                {
                    mc.AddProfile(new SourceMappingProfile());
                });
                IMapper mapper = mappingConfig.CreateMapper();
                _mapper = mapper;
            }

They make sure there is an instance of the automapper that is properly initialized with the correct profile.他们确保有一个使用正确配置文件正确初始化的自动映射器实例。

Ok, I've managed to solve the problem, it had nothing to do with the code above.好的,我已经设法解决了问题,它与上面的代码无关。 Just passed the wrong assembly to the profile constructor刚刚将错误的程序集传递给配置文件构造函数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM