![](/img/trans.png)
[英]AspNet.Core returns 200 OK and invalid Json if there is an exception while iterating an IEnumerable (returned from controller)
[英]Why Automapper returns null while mapping List<T> in aspnet.core 3.1?
在我的 .net 核心 3.1 中,我想使用自動映射器顯示嵌套元素。
在我的 dto 我有領域:
public class ServerChartDto
{
.. other values
public DiskSizeInfo DiskSize { get; set; }
}
public class DiskSizeInfo
{
public List<object> Projects { get; set; }
public long Total { get; set; }
}
我的映射器看起來像:
CreateMap<Organization, ServerChartDto>()
...other mappings
.ForMember(d => d.DiskSize, o => o.MapFrom(s => s.Projects
.Select(y => new DiskSizeInfo
{
Projects =
{
new
{
Name = y.Name,
Used = y.Servers.Sum(z => z.DiskSize)
}
},
Total = y.Servers.Sum(z => z.DiskSize)
}).ToList()))
想要結果如下:
diskSize: {
projects: [
{
name: 'fewregrge'
used: 234
}
],
total: 2342
}
您正在返回不兼容的類型:
public class ServerChartDto
{
.. other values
public DiskSizeInfo DiskSize { get; set; }
}
public class DiskSizeInfo
{
public List<object> Projects { get; set; }
public long Total { get; set; }
}
CreateMap<Organization, ServerChartDto>()
...other mappings
.ForMember(d => d.DiskSize, o => o.MapFrom(s => s.Projects
.Select(y => new DiskSizeInfo
{
Projects =
{
new
{
Name = y.Name,
Used = y.Servers.Sum(z => z.DiskSize)
}
},
Total = y.Servers.Sum(z => z.DiskSize)
}).ToList()))
ServerChartDto.DiskSize 的類型為 DiskSizeInfo
ForMember(d => d.DiskSize, o => o.MapFrom(s => s.Projects
.Select(y => new DiskSizeInfo
{
Projects =
{
new
{
Name = y.Name,
Used = y.Servers.Sum(z => z.DiskSize)
}
},
Total = y.Servers.Sum(z => z.DiskSize)
}).ToList()))
在前面的代碼中,您嘗試將d.DiskSize
設置為s.Projects.Select(y => y.newDiskSizeInfo...);
這是一個IEnumerable < DiskSizeInfo >.
正確的做法是:
ForMember(d => d.DiskSize, o => o.MapFrom(s => new DiskSizeInfo
{
Projects = s.Projects.Select(y => new
{
Name = y.Name,
Used = y.Servers.Sum(z => z.DiskSize)
}).ToList(),
Total = s.Projects.Sum(x => x.Servers.Sum(y => y.DiskSize)) //I assumed you wanted to sum the DiskSize of the Servers of each project
}))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.