c#-如何使用Automapper将一个源映射到多个目标?
发布时间:2022-03-02 01:58:04 243
相关标签: # flask
以下是示例:实体:
public class Contact
{
public int Id { get; set; }
......
public ICollection ContactDetails { get; set; }
}
public class ContactDetail
{
public Guid Id { get; set; }
public int ContactId { get; set; }
public ContactDetailTypes ContactDetailType { get; private set; }
public string Email { get; set; }
public string Address { get; set; }
public string Phone { get; set; }
......
}
public enum ContactDetailTypes : byte
{
Email = 1,
Phone = 2,
Address = 3,
......
}
视图模型:
public class ContactViewModel
{
public int Id { get; set; }
......
public ICollection ContactEmails { get; set; }
public ICollection ContactPhones { get; set; }
public ICollection ContactAddresses { get; set; }
}
public class ContactEmailViewModel
{
public Guid Id { get; set; }
public int ContactId { get; set; }
public string Email { get; set; }
}
public class ContactPhoneViewModel
{
public Guid Id { get; set; }
public int ContactId { get; set; }
public string Phone { get; set; }
}
public class ContactAddressViewModel
{
public Guid Id { get; set; }
public int ContactId { get; set; }
public string Address { get; set; }
}
我要映射联系人详细信息以联系MailViewModel、ContactPhoneViewModel、ContactAddressViewModel:
CreateMap()
.ForMember(dest => dest.Id, opts =>
{
opts.PreCondition(s => s.ContactDetailType == ContactDetailTypes.Email);
opts.MapFrom(src => src.Id);
})
.ForMember(dest => dest.ContactId, opts =>
{
opts.PreCondition(s => s.ContactDetailType == ContactDetailTypes.Email);
opts.MapFrom(src => src.ContactId);
})
.ForMember(dest => dest.Email, opts =>
{
opts.PreCondition(s => s.ContactDetailType == ContactDetailTypes.Email);
opts.MapFrom(src => src.Email);
});
(Phone, Address map are similar to above)
当我使用上述配置文件将Contact映射到ContactViewModel时,ContactEmail、ContactPhone和ContactAddresses的计数始终为0。我以为automapper可以检查detailType并将源映射到不同的目的地,但失败了。
如果我用这三个视图模型的所有属性创建一个ContactDetailViewModel,它会将所有属性从ContactDetail映射到ContactDetailViewModel。
在本例中,如何使用Automapper实现将一个源映射到多个目标?
更新:我添加了一张新地图,但仍然不走运:
CreateMap, ContactViewModel>()
.ForMember(dest => dest.ContactEmails, opts => opts.MapFrom(src => src.Where(s => s.ContactDetailType == ContactDetailTypes.Email)))
.ForMember(dest => dest.ContactPhones, opts => opts.MapFrom(src => src.Where(s => s.ContactDetailType == ContactDetailTypes.Phone)))
.ForMember(dest => dest.ContactAddresses, opts => opts.MapFrom(src => src.Where(s => s.ContactDetailType == ContactDetailTypes.Address)));
为什么我的帖子会被投入。。。我这么问是因为我在几次尝试后都找不到答案。。。
特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报