为什么当我尝试使用 AutoMapper 时出现异常?

我在 .NET CORE 2.2 项目中使用 AutoMapper。


我得到这个异常:


缺少类型映射配置或映射不受支持。映射类型:SaveFridgeTypeModel -> FridgeType College.Refrigirator.Application.SaveFridgeTypeModel -> College.Refrigirator.Domain.FridgeType


在这一行:


var fridgeType = _mapper.Map<SaveFridgeTypeModel, FridgeType>(model);

这是 FridgeType 类的定义:


public class FridgeType : IEntity , IType

{

    public FridgeType()

    {

        Fridges = new HashSet<Fridge>();

    }

    public int ID { get; set; }

    //Description input should be restricted 

    public string Description { get; set; }

    public string Text { get; set; }

    public ICollection<Fridge> Fridges { get; private set; }

}

这是 SaveFridgeTypeModel 类的定义:


public class SaveFridgeTypeModel

{

    public string Description { get; set; }

    public string Text { get; set; }

}

我添加这一行:


    services.AddAutoMapper(typeof(Startup));

Startup类中的ConfigureServices函数。


更新


我忘记在帖子中添加映射配置。


这是映射配置类:


public class ViewModelToEntityProfile : Profile

{

    public ViewModelToEntityProfile()

    {

        CreateMap<SaveFridgeTypeModel, FridgeType>();

    }

}

知道为什么我会得到上面的异常吗?


慕无忌1623718
浏览 44回答 2
2回答

叮当猫咪

在使用 DI 注册自动映射器时,您需要使用映射所在程序集中的类型。AddAutomapper(typeof(ViewModelToEntityProfile));如果您有多个带有地图的程序集 - 您可以使用另一个重载:AddAutomapper(typeof(ViewModelToEntityProfile),&nbsp;typeof(SomeOtherTypeInOtherAssembly));

萧十郎

Startup.cs创建映射配置类后,您需要在如下所示中添加 AutoMapperConfiguration :&nbsp; public void ConfigureServices(IServiceCollection services) {&nbsp; &nbsp; // .... Ignore code before this&nbsp; &nbsp;// Auto Mapper Configurations&nbsp; &nbsp; var mappingConfig = new MapperConfiguration(mc =>&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; mc.AddProfile(new ViewModelToEntityProfile());&nbsp; &nbsp; });&nbsp; &nbsp; IMapper mapper = mappingConfig.CreateMapper();&nbsp; &nbsp; services.AddSingleton(mapper);&nbsp; &nbsp; services.AddMvc();}
打开App,查看更多内容
随时随地看视频慕课网APP