EF Core 更新无法翻译 LINQ 表达式“x”

时间:2021-02-01 17:38:45

标签: entity-framework asp.net-core-5.0

我将我的 .net core 2.2 更新为 5

我有一个关于 ef 的错误

<块引用>

System.InvalidOperationException: 'LINQ 表达式 'x' 不能 被翻译。要么以可以是的形式重写查询 翻译,或通过插入一个显式切换到客户评估 调用“AsEnumerable”、“AsAsyncEnumerable”、“ToList”或 'ToListAsync'。参见https://go.microsoft.com/fwlink/?linkid=2101038 更多信息。'

public List<CustomerPageModel> GetCustomers(int AccountID)
        {
            return (from p in context.Customers
                    join f in context.Patients on p.ID equals f.CustomerID into ps
                    from t in ps.DefaultIfEmpty()
                    where p.AccountID == AccountID
                    select new CustomerPageModel
                    {
                        ID = p.ID,
                        Name = p.Name,
                        IsActive = p.IsActive,
                        TC = p.TC,
                        Surname = p.Surname,
                        Email = p.Email,
                        Address = p.Address,
                        Phone = p.Phone,
                        Note = p.Note,
                        AccountID = p.AccountID,
                        Pats = string.Join(",", ps.Select(x => x.Name)),
                        PatCount = ps.Count()
                    })
            .GroupBy(p => p.ID)
            .Select(g => g.First())
           .ToList();
        }

如何转换该代码?

2 个答案:

答案 0 :(得分:1)

您的问题是:

Pats = string.Join(",", ps.Select(x => x.Name)),

具体来说,string.Join 方法不会转换为 SQL,因此在以前版本的 EF 中,它必须从数据库中检索数据,然后在内存中执行 string.Join 函数。现在 EF 明确地告诉你它不能在数据库服务器上运行——这是一个重大变化,但一个设计决策告诉你(开发人员)它可能没有像你想象的那样高效地运行......< /p>

要“修复”此问题,并且根据您的特定代码示例,我建议您执行以下操作:

向 CustomerPageModel 添加宠物名称数组属性:

public string[] PetNames {get;set;}

并将 Pets 属性转换为只读计算字符串:

public string Pets { get => string.Join(",", PetNames); }

并将 LINQ 表达式中的问题行更改为:

PetNames = ps.Select(x => x.Name).ToArray()

答案 1 :(得分:-2)

我改变了(羔羊到子查询)

string.Join(",", ps.Select(x => x.Name)) 

string.Join(",", (from y in PatientList where y.CustomerID == p.ID select y.Name).ToArray()),

我是后来组的(在tolist之后)

var test = mylist.GroupBy(p => p.ID)
                .Select(g => g.First())
                .ToList();

问题已解决