EF核心区别+ OrderBy引发翻译错误

时间:2020-08-03 21:13:24

标签: c# linq entity-framework-core

我一直在处理一个非常令人沮丧的EF Core(最新版本)错误。在这一点上,我不确定我做错了什么还是错误。社区可以提供的任何帮助将不胜感激。

该错误与Entity Framework Core有关,并且将LINQ表达式转换为SQL。以下代码可正确转换为SQL。下面的查询变量可能会毫无问题地应用于各种Where表达式和Includes。

// This works fine
query.Select(price => new Customer {
   Name = price.Payer.Name,
   Code = price.Payer.Code,
   City = price.Payer.City,
   ParentCode = price.Payer.ParentCode,
   ParentLevel = CustomerLevel.Corporate,
   CustomerLevel = CustomerLevel.Payer
}).Distinct().ToListAsync();



一旦我添加对OrderBy的呼叫,它将不会评估。如果我删除对Distinct的呼叫,它将再次起作用,但是我不能同时拥有两者。我尝试了几种不同的方式来构建表达式,以及在interwebz上发现的几种变通办法,似乎没有任何解决办法。

// This throws error
// query is of type IQueryable<Price>
query.Select(price => new Customer {
   Name = price.Payer.Name,
   Code = price.Payer.Code,
   City = price.Payer.City,
   ParentCode = price.Payer.ParentCode,
   ParentLevel = CustomerLevel.Corporate,
   CustomerLevel = CustomerLevel.Payer
}).Distinct().OrderBy(cust => cust.Name).ToListAsync();



另外,OrderBy的位置似乎无关紧要。根据我的阅读,对Distinct的调用会删除所有先前的顺序,因此这一点并不奇怪。

// This also throws error
// query is of type IQueryable<Price>
query
   .OrderBy(price => price.payer.Name)
   .Select(price => new Customer {
      Name = price.Payer.Name,
      Code = price.Payer.Code,
      City = price.Payer.City,
      ParentCode = price.Payer.ParentCode,
      ParentLevel = CustomerLevel.Corporate,
      CustomerLevel = CustomerLevel.Payer
   }).Distinct().ToListAsync();

1 个答案:

答案 0 :(得分:0)

我今天实际上找到了问题的原因。 ParentCode属性(在行ParentCode = price.Payer.ParentCode中使用)实际上是未映射到表的基类上的属性,因此EF显然不知道该如何处理。其中最奇怪的部分是它在没有OrderBy的情况下可以工作。将该行更改为ParentCode = price.Payer.CorporateCode解决了该问题。

感谢所有浏览过此内容的人。