AutoMapperMappingException:错误映射类型

时间:2018-04-07 08:42:22

标签: c# automapper

我的解决方案中有以下课程:

    public class VehicleMakeEntity
    {
      public Guid Id { get; set; }

      public string Name { get; set; }

      public ICollection<VehicleModelEntity> VehicleModels { get; set; }
    }

    public class VehicleModelEntity
    {
      public Guid Id { get; set; }

      public Guid VehicleMakeId { get; set; }

      public string Name { get; set; }

      public VehicleMakeEntity VehicleMake { get; set; }
    }


    public class VehicleMake : IVehicleMake
    {
      public Guid Id { get; set; }

      public string Name { get; set; }

      public ICollection<IVehicleModel> VehicleModels { get; set; }
    }

    public class VehicleModel : IVehicleModel
    {
      public Guid Id { get; set; }

      public Guid VehicleMakeId { get; set; }

      public string Name { get; set; }

      public IVehicleMake VehicleMake { get; set; }
    }

我有以下界面:

public interface IVehicleMake
{
    Guid Id { get; set; }

    string Name { get; set; }

    ICollection<IVehicleModel> VehicleModels { get; set; }
}

public interface IVehicleModel
{
    Guid Id { get; set; }

    Guid VehicleMakeId { get; set; }

    string Name { get; set; }

    IVehicleMake VehicleMake { get; set; }
}

我的AutoMapper配置如下:

            AutoMapper.Mapper.Initialize(cfg =>
            {
              cfg.CreateMap<VehicleMakeEntity, VehicleMake>().ReverseMap();
              cfg.CreateMap<VehicleMakeEntity, IVehicleMake>().ReverseMap();
              cfg.CreateMap<IVehicleMake, VehicleMake>().ReverseMap();
              cfg.CreateMap<VehicleModelEntity, VehicleModel>().ReverseMap();
              cfg.CreateMap<VehicleModelEntity, IVehicleModel>().ReverseMap();
              cfg.CreateMap<IVehicleModel, VehicleModel>().ReverseMap();
            });

当我尝试做这样的事情时:

var makes = Context.VehicleMakes.AsQueryable();

var vehicleMakes = await makes.Include(m => m.VehicleModels).ToListAsync();

return new List<IVehicleMake>(AutoMapper.Mapper.Map<List<VehicleMake>>(vehicleMakes));

我得到映射类型错误:VehicleModelEntity - &gt; IVehicleModel。

我想我没有正确创建映射。我应该如何配置我的映射以避免这种情况?

1 个答案:

答案 0 :(得分:0)

映射配置似乎是正确的。 QueryableExtensions.ToListAsync方法返回Task<List<T>>,尝试在映射中传递vehicleMakes.Result