C# AutoMapper 简化
C# AutoMapper simplification
有什么方法可以简化映射?我不想写 src.Accounts.First().UserInfo
多次访问。最好将它放在一个单独的变量中。怎么做?
CreateMap<Test, TestDto>()
.ForMember(dst => dst.FirstName, opt => opt.MapFrom(src => src.Accounts.First().UserInfo.FirstName))
.ForMember(dst => dst.LastName, opt => opt.MapFrom(src => src.Accounts.First().UserInfo.LastName))
.ForMember(dst => dst.Email, opt => opt.MapFrom(src => src.Accounts.First().UserInfo.Email));
谢谢
您可以使用 IncludeMembers
.
CreateMap<Test, TestDto>().IncludeMembers(src => src.Accounts.First().UserInfo);
https://docs.automapper.org/en/latest/Flattening.html#includemembers
public class TestDtoTypeResolver : ITypeConverter<Test, TestDto>
{
public TestDto Convert(Test source, TestDto destination, ResolutionContext context)
{
var userInfo = source.Accounts.First().UserInfo;
return new TestDto
{
FirstName = userInfo.FirstName,
LastName = userInfo.LastName,
Email = userInfo.Email
};
}
}
CreateMap<Test, TestDto>()
.ConvertUsing<TestDtoTypeResolver>();
有什么方法可以简化映射?我不想写 src.Accounts.First().UserInfo
多次访问。最好将它放在一个单独的变量中。怎么做?
CreateMap<Test, TestDto>()
.ForMember(dst => dst.FirstName, opt => opt.MapFrom(src => src.Accounts.First().UserInfo.FirstName))
.ForMember(dst => dst.LastName, opt => opt.MapFrom(src => src.Accounts.First().UserInfo.LastName))
.ForMember(dst => dst.Email, opt => opt.MapFrom(src => src.Accounts.First().UserInfo.Email));
谢谢
您可以使用 IncludeMembers
.
CreateMap<Test, TestDto>().IncludeMembers(src => src.Accounts.First().UserInfo);
https://docs.automapper.org/en/latest/Flattening.html#includemembers
public class TestDtoTypeResolver : ITypeConverter<Test, TestDto>
{
public TestDto Convert(Test source, TestDto destination, ResolutionContext context)
{
var userInfo = source.Accounts.First().UserInfo;
return new TestDto
{
FirstName = userInfo.FirstName,
LastName = userInfo.LastName,
Email = userInfo.Email
};
}
}
CreateMap<Test, TestDto>()
.ConvertUsing<TestDtoTypeResolver>();