c# - 'System.Linq.Expressions.ParameterExpression' 必须返回相同类型的非空值 - 在 EF API 调用上
问题描述
我正在尝试int
使用以下代码填充 .NET Core 3.1 API 控制器(使用 Entity Framework Core)中的类的属性:
[HttpGet("Get")]
public async Task<ActionResult<IEnumerable<Partner>>> Get()
{
List<Device> devices = await _context.Devices.ToListAsync();
List<Partner> items = await (from p in _context.Partners
select new Partner
{
Id = p.Id,
Name = p.Name,
FiscalCode = p.FiscalCode,
Licenses = p.Licenses,
Erp = p.Erp,
ErpName = p.Erp == 1 ? "Erp 1" : "Erp 2",
Devices = devices.Count(k => k.PartnerId == p.Id)
}).OrderBy(k => k.Name).ToListAsync();
return items;
}
该Devices = devices.Count(k => k.PartnerId == p.Id)
行生成以下错误:
System.InvalidOperationException: When called from 'VisitLambda', rewriting a node of type 'System.Linq.Expressions.ParameterExpression' must return a non-null value of the same type
我究竟做错了什么?
提前致谢
解决方案
我认为您正在尝试在数据库中进行联接和分组。这样,您只需在数据库中查询一次,因此性能更好。
尝试这个:
List<Partner> items = await(from p in _context.Partners
join d in _context.Devices
on p.Id equals d.PartnerId
group d by d.Partner /*relation property*/ into g
select new Partner
{
Id = g.Key.Id,
Name= g.Key.Name,
DeviceCount=g.Count()
// select other your properties here
}).OrderBy(k => k.Name).ToListAsync();
但是,如果您想继续执行不推荐的操作,请尝试将Partner表放入内存中,然后从内存表中的这些表中选择数据。像这样:
var partners=await _context.Partners.ToListAsync();
推荐阅读
- angular10 - 如何知道用户何时离开您的 Angular 应用程序
- npm - 如何将 npm 包从 artifactory 镜像到 verdaccio?
- cordova - 在科尔多瓦应用程序中加载白屏
- r - R中的层次聚类
- exit - EasyPHP 17.0 HTTP 服务器警告和通知
- r - 过滤器向量(读取最近的文件名)
- arduino - 带有 LTC6820 的长距离 Arduino 多 NFC 读取器 RC522
- intellij-idea - IntelliJ Idea 忽略 Maven 默认配置文件
- ssl - 多域证书
- microsoft-graph-api - Microsoft Graph 自动化 Powershell 脚本