首页 > 解决方案 > '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

我究竟做错了什么?

提前致谢

标签: c#entity-framework-coreasp.net-core-3.1.net-core-3.1

解决方案


我认为您正在尝试在数据库中进行联接分组。这样,您只需在数据库中查询一次,因此性能更好

尝试这个:

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();

推荐阅读