gpt4 book ai didi

c# - 用于对数据进行分组的自动映射器配置

转载 作者:行者123 更新时间:2023-12-02 20:20:31 25 4
gpt4 key购买 nike

我有以下型号

来源:

public class Opportunity
{
public Guid Id { get; set; }
public string Name { get; set; }
public Guid QuotationId { get; set; }
public int? QuotationNumber { get; set; }
public int? QuotationVersionNumber { get; set; }
}

目标:

public class OpportunityDto
{
public Guid Id { get; set; }
public string Name { get; set; }
public List<QuotationDto> Quotations { get; set; }
}

public class QuotationDto
{
public Guid Id { get; set; }
public int Number { get; set; }
public int VersionNumber { get; set; }
}

我从数据库中获取的数据将与 Opportunity 模型保持一致,并且我的 api 正在公开 OpportunityDto 模型。因此,在我的自动映射器配置中,我有以下代码:

services
.AddSingleton(new MapperConfiguration(cfg =>
{
cfg.CreateMap<OpportunityDto, Opportunity>().ReverseMap();
cfg.CreateMap<QuotationDto, Quotation>().ReverseMap();
}).CreateMapper())

我想要实现的是一个独特机会的列表,每个机会都有一个嵌套成员,其中包含报价列表。如何让自动映射器执行此分组?现在,从 api 返回的 opportunityDto 的 Quotations 成员始终为空。

最佳答案

自动映射器配置

您可以执行以下操作:

    public static void InitialiseMapper()
{
Mapper.Initialize(cfg =>
{
cfg.CreateMap<IEnumerable<Opportunity>, OpportunityDto>()
.ForMember(x => x.Id, x => x.MapFrom(y => y.FirstOrDefault().Id))
.ForMember(x => x.Name, x => x.MapFrom(y => y.FirstOrDefault().Name))
.ForMember(x => x.Quotations,
x => x.MapFrom(y => Mapper.Map<IEnumerable<Opportunity>, IEnumerable<QuotationDto>>(y).ToArray()))
;

cfg.CreateMap<Opportunity, QuotationDto>()
.ForMember(x => x.Id, x => x.MapFrom(y => y.QuotationId))
.ForMember(x => x.Number, x => x.MapFrom(y => y.QuotationNumber))
.ForMember(x => x.VersionNumber, x => x.MapFrom(y => y.QuotationVersionNumber))
;
});
}

测试

然后成功地知道如何映射,如以下测试所示:

    [TestMethod]
public void TestMethod1()
{
var oppo1Guid = Guid.NewGuid();

var opportunities = new List<Opportunity>
{
new Opportunity
{
Id = oppo1Guid,
Name = "Mikeys Oppurtunity",
QuotationId = Guid.NewGuid(),
QuotationNumber = 169,
QuotationVersionNumber = 80,
},

new Opportunity
{
Id = oppo1Guid,
Name = "Mikeys Oppurtunity",
QuotationId = Guid.NewGuid(),
QuotationNumber = 170,
QuotationVersionNumber = 20,
}
};

var dtos = Mapper.Map<IEnumerable<Opportunity>, OpportunityDto>(opportunities);

var json = JsonConvert.SerializeObject(dtos, Formatting.Indented);

Console.WriteLine(json);
}

输出是

测试输出

{
"Id": "623c17df-f748-47a2-bc7e-35eb124dbfa3",
"Name": "Mikeys Oppurtunity",
"Quotations": [
{
"Id": "ad8b31c2-6157-4b7f-a1f2-9f8cfc1474b7",
"Number": 169,
"VersionNumber": 80
},
{
"Id": "515aa560-6a5b-47da-a214-255d1815e153",
"Number": 170,
"VersionNumber": 20
}
]
}

关于c# - 用于对数据进行分组的自动映射器配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51503133/

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