代码之家  ›  专栏  ›  技术社区  ›  GoGo

使用LINQ将DTO类中的变量映射到

  •  1
  • GoGo  · 技术社区  · 6 年前

    我有两个班叫 Participant Screen .

    public class Participant 
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    
        public ICollection<Screen> Screens { get; set; }
    }
    
    
    
    public class Screen
    {
        public int Id { get; set; }
        public DateTime? SignedDateTime { get; set; }
    }
    

    我用的是 DTO 如下:

    public class ParticipantForDashboardDto
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string MiddleName { get; set; }
        public string LastName { get; set; }
        public DateTime? ScreenDateTime { get; set; }
    
        public ICollection<Screen> Screens { get; set; }
    }
    

    在这里,因为我没有 ScreenDateTime 我的领域 参与者 同学们,我决定从 屏幕 类使用 AutoMapper . 这是我的 MappingProfile :

    CreateMap<Participant, ParticipantForDashboardDto>()
            .ForMember(dest => dest.ScreenDateTime, opt => {
                    opt.MapFrom(src => src.Screens.Select(x => x.SignedDateTime));
                });
    

    这种回报 0001-01-01T00:00:00 . 我怀疑 SELECT 查询不是我应该使用的查询。我如何映射 SignedDateTime 屏幕 类到 ScreenDate 在DTO中?

    1 回复  |  直到 6 年前
        1
  •  1
  •   johnny 5    6 年前

    您当前使用的是可查询的,它将返回多个结果,您可能需要一个结果,因此您需要创建一种方法来解决正确的结果,例如排序和第一个或默认:

    CreateMap<Participant, ParticipantForDashboardDto>()
        .ForMember(dest => dest.ScreenDateTime, opt => {
                opt.MapFrom(src => src.Screens.Select(x => x.SignedDateTime)
                                              .OrderByDescending(x => x)
                                              .FirstOrDefault());
        });