gpt4 book ai didi

c# - AutoMapper - 展平/展平列表

转载 作者:太空宇宙 更新时间:2023-11-03 14:45:15 25 4
gpt4 key购买 nike

我想将我的 Entity Framework 模型数据扁平化为我的 ASP.NET Core REST Web 服务的 dto。

我的实体类(简化版)如下所示:

public class DeliveryNoteEntity
{
public string VehicleNo { get; set; }
public int NotMapped { get; set; }
public List<DeliveryNoteSignature> Signatures { get; set; }
}

public class DeliveryNoteSignature
{
public string Signature { get; set; }
public SignedByRole SignedBy { get; set; }
}

public enum SignedByRole
{
Driver = 1,
Recipient = 2
}

我的dto看起来像

public class DeliveryNoteDto
{
public int Id { get; set; }
public string VehicleNo { get; set; }
public string DriverSignature { get; set; }
public string RecipientSignature { get; set; }
}

然后我可以像这样填充我的实体

var sourceEntity = new DeliveryNoteEntity
{
VehicleNo = "VehicleNo20",
Signatures = new List<DeliveryNoteSignature> { new DeliveryNoteSignature { Signature = "Driver Mr. Pitz", SignedBy = SignedByRole.Driver} }
};

并映射到一个dto:

Mapper.Initialize(cfg => cfg.CreateMap<DeliveryNoteEntity, DeliveryNoteDto>()
.ForMember(dest => dest.DriverSignature, opt => opt.MapFrom(src => src.Signatures
.Where(x => x.SignedBy == SignedByRole.Driver)
.Select(x => x.Signature)
.FirstOrDefault()))
.ForMember(dest => dest.RecipientSignature, opt => opt.MapFrom(src => src.Signatures
.Where(x => x.SignedBy == SignedByRole.Recipient)
.Select(x => x.Signature)
.FirstOrDefault()))
.ReverseMap()
);
var dto = Mapper.Map<DeliveryNoteDto>(sourceEntity);

所以我的问题是:当实体返回到我的服务时,如何进行从 dto 到实体的反向映射?所以我会用手做这样的事情:

var entityToSave = new DeliveryNoteEntity()
{
VehicleNo = dto.VehicleNo,
Signatures = new List<DeliveryNoteSignature>
{
new DeliveryNoteSignature {SignedBy = SignedByRole.Driver, Signature = dto.DriverSignature},
new DeliveryNoteSignature {SignedBy = SignedByRole.Recipient, Signature = dto.RecipientSignature}
}
};

有什么方法可以用 AutoMapper 实现吗?

编辑:我真正的问题是如何从我的 dto 中的 XXXSignature 属性映射到我的实体中的列表?

最佳答案

如果您使用 AutoMapper 的命名约定,ReverseMap 也已为您完成。

class CustomerClass
{
public string Name {get; set;}
public string Surname {get;set;}
}

class MainClass
{
public CustomerClass Customer {get; set;}
}

class MainClassDto
{
public string CustomerName {get; set;}
public string CustomerSurname {get; set;}

}

对于此示例,您不需要为映射和/或反向映射进行任何配置。 AutoMapper 使用其默认配置处理它

关于c# - AutoMapper - 展平/展平列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54554705/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com