从 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());
}
}
在 automapper 实例中它可能为 null。您添加了这个吗:
services.AddAutoMapper()
?
https://docs.automapper.org/en/stable/Dependency-injection.html