【问题标题】:Map ICollection With AutoMapper使用 AutoMapper 映射 ICollection
【发布时间】:2021-05-19 15:22:44
【问题描述】:

大家好,我在使用 AutoMapper 映射某些模型时遇到了很多麻烦,我想知道您能否指出正确的方向。

我有一些实体如下;

      public class Camp
  {
    public int CampId { get; set; }
    public string Name { get; set; }
    public string Moniker { get; set; }
    public Location Location  { get; set; }
    public DateTime EventDate { get; set; } = DateTime.MinValue;
    public int Length { get; set; } = 1;
    public ICollection<Talk> Talks { get; set; }
  }



 public class Talk
  {
    public int TalkId { get; set; }
    public Camp Camp { get; set; }
    public string Title { get; set; }
    public string Abstract { get; set; }
    public int Level { get; set; }
    public Speaker Speaker { get; set; }
  }

以及对应的DTO的

   public class CampModel
    {

        public string Name { get; set; }
        public string Moniker { get; set; }
        public DateTime EventDate { get; set; } = DateTime.MinValue;
        public int Length { get; set; } = 1;

        public string Venue { get; set; }
        public string LocationAddress1 { get; set; }
        public string LocationAddress2 { get; set; }
        public string LocationAddress3 { get; set; }
        public string LocationCityTown { get; set; }
        public string LocationStateProvince { get; set; }
        public string LocationPostalCode { get; set; }
        public string LocationCountry { get; set; }
        public ICollection<TalkModel> Talks { get; set; }

    }


 public class TalkModel
    {
        public int TalkId { get; set; }
        public string Title { get; set; }
        public string Abstract { get; set; }
        public int Level { get; set; }
    }

我想在我的控制器上使用自动映射器,如下所示:

 [Route("api/[controller]")]
    public class CampsController : ControllerBase
    {
        private readonly ICampRepository _repository;
        private readonly IMapper _mapper;

        public CampsController(ICampRepository repository, IMapper mapper)
        {
            _repository = repository;
            _mapper = mapper;
        }
      

        [HttpGet]
        public async Task<ActionResult<CampModel[]>> Get(bool includeTalks = false)
        {
            try
            {
                var camps = await _repository.GetAllCampsAsync(includeTalks);

                var mapper = _mapper.Map<CampModel[]>(camps);


                return mapper;
            }
            catch (Exception e)
            {
                return StatusCode(StatusCodes.Status500InternalServerError, "Database failure" + " Message: " + e);
            }
        }
}

我正在像这样返回我的存储库中的营地:

  public async Task<Camp[]> GetAllCampsByEventDate(DateTime dateTime, bool includeTalks = false)
    {
      _logger.LogInformation($"Getting all Camps");

      IQueryable<Camp> query = _context.Camps
          .Include(c => c.Location);

      if (includeTalks)
      {
        query = query
          .Include(c => c.Talks)
          .ThenInclude(t => t.Speaker);
      }

      // Order It
      query = query.OrderByDescending(c => c.EventDate)
        .Where(c => c.EventDate.Date == dateTime.Date);

      return await query.ToArrayAsync();
    }

我已经在 Startup.Cs 上注册了我的自动映射器

 services.AddAutoMapper(typeof(CampProfile).Assembly);

像这样使用配置文件:

 public class CampProfile : Profile
    {

        public CampProfile()
        {
            this.CreateMap<Camp, CampModel>()
                .ForMember(c => c.Venue, o => o.MapFrom(m => m.Location.VenueName))
                .ForMember(c => c.Talks, o => o.MapFrom(m => m.Talks))
                .ReverseMap();
        }
        
    }

但是当我尝试点击我的端点时,我收到以下错误:

Message: AutoMapper.AutoMapperMappingException: Error mapping types.

Mapping types:
Object -> CampModel[]
System.Object -> CoreCodeCamp.Models.CampModel[]
 ---> AutoMapper.AutoMapperMappingException: Error mapping types.

Mapping types:
Camp -> CampModel
CoreCodeCamp.Data.Camp -> CoreCodeCamp.Models.CampModel

Type Map configuration:
Camp -> CampModel
CoreCodeCamp.Data.Camp -> CoreCodeCamp.Models.CampModel

Destination Member:
Talks

 ---> AutoMapper.AutoMapperMappingException: Missing type map configuration or unsupported mapping.

Mapping types:
Talk -> TalkModel
CoreCodeCamp.Data.Talk -> CoreCodeCamp.Models.TalkModel

我做错了什么?我认为问题与public ICollection&lt;Talk&gt; Talks { get; set; } 属性有关。提前致谢

【问题讨论】:

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


    【解决方案1】:

    只需在Talk 和TalkModel 之间添加映射器,如下所示:

    public class CampProfile : Profile
    {
    
        public CampProfile()
        {
            this.CreateMap<Talk, TalkModel>();
            this.CreateMap<Camp, CampModel>()
                .ForMember(c => c.Venue, o => o.MapFrom(m => m.Location.VenueName))
                //.ForMember(c => c.Talks, o => o.MapFrom(m => m.Talks))
                .ReverseMap();
        }
    
    }
    

    【讨论】:

    • 不需要Talks 配置。
    【解决方案2】:

    根据您上面提供的代码,您需要在 Talk 和 TalkModel 之间配置映射,请在 AutoMapper 中查看 Nested Mappings。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-25
      相关资源
      最近更新 更多