【问题标题】:Why I get exception when I try to use AutoMapper?为什么我在尝试使用 AutoMapper 时会出现异常?
【发布时间】:2019-09-30 10:24:32
【问题描述】:

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

我得到了这个例外:

缺少类型映射配置或不支持的映射。 映射类型: SaveFridgeTypeModel -> 冰箱类型 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>();
    }
}

知道为什么会出现上述异常吗?

【问题讨论】:

  • 你需要先配置映射,见:stackoverflow.com/q/40275195/1875256
  • 正如错误所说,没有从SaveFridgeModelTypeFridgeType 的映射。
  • @VidmantasBlazevicius 请查看更新
  • ViewModelToEntityProfile 是否与Startup 在同一个程序集中?通过写AddAutomapper(typeof(Startup)),你基本上说只从这个程序集中获取地图
  • 我的意思是我猜阻力最小的路径是AddAutomapper(typeof(ViewModelToEntityProfile))

标签: c# .net .net-core automapper


【解决方案1】:

在向 DI 注册 automapper 时,您需要使用地图所在程序集中的类型。

AddAutomapper(typeof(ViewModelToEntityProfile));

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

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

【讨论】:

    【解决方案2】:

    创建映射配置类后需要在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();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-28
      • 1970-01-01
      • 1970-01-01
      • 2013-11-13
      • 1970-01-01
      相关资源
      最近更新 更多