Automapper 给出一个空对象?

问题描述 投票:0回答:1

从 Automapper 获取空对象

[09:25:23 ERR] System.NullReferenceException: Object reference not set to an instance of an object.
   at lambda_method501(Closure, Object, RoomLogic, ResolutionContext)
   at AutoMapper.Mapper.MapCore[TSource,TDestination](TSource source, TDestination destination, ResolutionContext context, Type sourceType, Type destinationType, MemberMap memberMap)
   at AutoMapper.Mapper.Map[TSource,TDestination](TSource source, TDestination destination)
   at AutoMapper.Mapper.Map[TDestination](Object source)

这是我的映射方式:

var roomLogic = mapper.Map<RoomLogic>(room);

简介:

public class RoomProfile : Profile
{
    public RoomProfile(IServiceProvider serviceProvider)
    {
        CreateMap<Room, RoomLogic>()
            .ConstructUsing(x => new RoomLogic(
                x.Id));
    }
}

课程:

public class Room
{
    public int Id { get; set; }
}

public class RoomLogic : Room
{
    public RoomLogic(int id)
    {
        Id = id;
    }
}

注册:

public static class MapperServiceCollection
{
    public static void AddServices(IServiceCollection serviceCollection, IConfiguration config)
    {
        serviceCollection.AddSingleton<RoomProfile>();
        serviceCollection.AddSingleton(provider => new MapperConfiguration(c =>
        {
            c.AddProfile(provider.GetRequiredService<RoomProfile>());
        }).CreateMapper());
    }
}
c# automapper
1个回答
-1
投票

在 automapper 实例中它可能为 null。您添加了这个吗:

services.AddAutoMapper()

https://docs.automapper.org/en/stable/Dependency-injection.html

© www.soinside.com 2019 - 2024. All rights reserved.