gpt4 book ai didi

c# - 如何手动将带有列表的 View 模型映射到 dto

转载 作者:行者123 更新时间:2023-11-30 18:17:27 25 4
gpt4 key购买 nike

我是后端开发的新手,在将 View 模型映射到具有列表的 dto 时遇到了一些问题。

你能帮我弄清楚映射器有什么问题吗?结果来自 dto 是正确的。我有一个包含 7 个项目的列表。当它映射到 View 时,它们就消失了。

这是 View 模型

public class StatisticsViewModel : BaseViewModel
{
public string StartDate { get; set; }
public string EndDate { get; set; }
public string ProviderId { get; set; }
public List<StatisticsTotalsViewModel> Totals { get; set; } = new List<StatisticsTotalsViewModel>();
public List<StatisticsProvidersViewModel> Providers { get; set; } = new List<StatisticsProvidersViewModel>();
}

public class StatisticsTotalsViewModel
{
public string PayerName { get; set; }
public string PayerType { get; set; }
public short Status { get; set; }
public int TotalCount { get; set; }
public decimal TotalBalance { get; set; }
}

这是dto

public class StatisticsDto
{
public string StartDate { get; set; }
public string EndDate { get; set; }
public string ProviderId { get; set; }
public List<StatisticsTotalsDto> Totals { get; set; } = new List<StatisticsTotalsDto>();
public List<StatisticsProvidersDto> Providers { get; set; } = new List<StatisticsProvidersDto>();
}

public class StatisticsTotalsDto
{
public string PayerName { get; set; }
public string PayerType { get; set; }
public short Status { get; set; }
public int TotalCount { get; set; }
public decimal TotalBalance { get; set; }
}

这是映射器

    public static StatisticsViewModel MapToView(StatisticsDto dto)
{
var viewmodel = new StatisticsViewModel();

viewmodel.StartDate = dto.StartDate;
viewmodel.EndDate = dto.EndDate;
viewmodel.ProviderId = dto.ProviderId;

var dtoTotals = new List<StatisticsTotalsDto>();
var totals = new List<StatisticsTotalsViewModel>();

foreach (var item in dtoTotals)
{
var totalsModel = new StatisticsTotalsViewModel();
item.PayerName = totalsModel.PayerName;
item.PayerType = totalsModel.PayerType;
item.Status = totalsModel.Status;
item.TotalBalance = totalsModel.TotalBalance;
item.TotalCount = totalsModel.TotalCount;
totals.Add(totalsModel);
}

viewmodel.Totals = totals;

return viewmodel;

}

最佳答案

这一行有问题。相反

var dtoTotals = new List<StatisticsTotalsDto>();

您需要接收 StatisticsTotalsDto 列表,而不是创建新的空列表

var dtoTotals = dto.Totals;

关于c# - 如何手动将带有列表的 View 模型映射到 dto,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43621890/

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