为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
慕无忌1623718 2024-01-20 21:44:50
我在 .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>();    }}知道为什么我会得到上面的异常吗?
查看完整描述

2 回答

?
叮当猫咪

TA贡献1776条经验 获得超12个赞

在使用 DI 注册自动映射器时,您需要使用映射所在程序集中的类型。

AddAutomapper(typeof(ViewModelToEntityProfile));

如果您有多个带有地图的程序集 - 您可以使用另一个重载:

AddAutomapper(typeof(ViewModelToEntityProfile), typeof(SomeOtherTypeInOtherAssembly));



查看完整回答
反对 回复 2024-01-20
?
萧十郎

TA贡献1815条经验 获得超12个赞

Startup.cs创建映射配置类后,您需要在如下所示中添加 AutoMapperConfiguration :


  public void ConfigureServices(IServiceCollection services) {

    // .... Ignore code before this


   // Auto Mapper Configurations

    var mappingConfig = new MapperConfiguration(mc =>

    {

        mc.AddProfile(new ViewModelToEntityProfile());

    });


    IMapper mapper = mappingConfig.CreateMapper();

    services.AddSingleton(mapper);


    services.AddMvc();

}


查看完整回答
反对 回复 2024-01-20
  • 2 回答
  • 0 关注
  • 40 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信