注意:我从未解决过这个问题,只是继续使用直接的Linq查询。 .Select(a => new UserDetailsDto { ContactId = a.ContactId, etc
我遇到的问题是试图了解Automapper如何用于在一个查询中将导航属性与父实体进行映射。
假设我有一个与实体密切相关的UserDto,看起来像这样:
public class User
{
public int UserId { get; set; }
public int UserDetailsId { get; set; }
public int ContactId { get; set; }
public DateTime CreateDateTime { get; set; }
public DateTime? ModifiedDateTime { get; set; }
public DateTime? InactiveDateTime { get; set; }
public UserDetail UserDetails { get; set; }
}
然后我有一个名为UserDetail的实体,它主要由导航属性组成(我只发布一些道具以保持简短):
public partial class UserDetail
{
public int UserDetailId { get; set; }
public int UsertId { get; set; }
public DateTime? DateOfBirth { get; set; }
public int? ProviderId { get; set; }
public int? FacilityId { get; set; }
public int? CarrierId { get; set; }
public int? GenderId { get; set; }
public int? EthnicityId { get; set; }
}
然后是它的DTO
public class UserDetailDto
{
public int ParticipantDetailId { get; set; }
public int ParticipantId { get; set; }
public DateTime DateOfBirth { get; set; }
public string Provider { get; set; }
public string Facility { get; set; }
public string Carrier { get; set; }
public string Gender { get; set; }
public string Ethnicity { get; set; }
}
我已经看到你可以使用类似的东西:
IEnumerable<UserDto> users = await
db.DbContext.Set<User>()
.ProjectTo<UserDto>()
.ToListAsync();
但我不知道如何将其与Mapper配置中的.ForMember
结合使用。
我只是展示了我所见过的东西。对于如何实现这一点,我完全愿意接受任何建议。
修改
Mapper配置:
config.CreateMap<User, UserDto>();
config.CreateMap<UserDto, User>();
config.CreateMap<UserDetail, UserDetailDto>()
.ForMember(dto => dto.Provider, conf => conf.MapFrom(entity => entity.Provider.ProviderName))
.ForMember(dto => dto.Facility, conf => conf.MapFrom(entity => entity.Facility.FacilityName))
.ForMember(dto => dto.Carrier, conf => conf.MapFrom(entity => entity.Carrier.CarrierName))
.ForMember(dto => dto.Gender, conf => conf.MapFrom(entity => entity.Gender.GenderText))
.ForMember(dto => dto.Ethnicity, conf => conf.MapFrom(entity => entity.Ethnicity.EthnicityText))
.ForMember(dto => dto.Orientation, conf => conf.MapFrom(entity => entity.Orientation.OrientationText))
.ForMember(dto => dto.Education, conf => conf.MapFrom(entity => entity.Education.EducationText))
.ForMember(dto => dto.Employment, conf => conf.MapFrom(entity => entity.Employment.EmploymentText))
.ForMember(dto => dto.EarningRange, conf => conf.MapFrom(entity => entity.EarningRange.EarningRangeText))
.ForMember(dto => dto.Language, conf => conf.MapFrom(entity => entity.Language.LanguageCode))
.ForMember(dto => dto.CallTimeId, conf => conf.MapFrom(entity => entity.CallTime.CallTimeText));
config.CreateMap<ParticipantDetailDto, ParticipantDetail>();
config.CreateMap<UserDetailDto, UserDetail>();