[英]The LINQ expression could not be translated
I have a table called Orders
and a list called Customers
.我有一个名为Orders
的表和一个名为Customers
的列表。 Orders
has a property CustomerId
. Orders
有一个属性CustomerId
。 Now I want to get all orders of customers that are in my Customers
list.现在我想获取我的Customers
列表中的所有客户订单。
This is what I tried:这是我尝试过的:
IEnumerable<Customer> customers; // list of customers
List<Order> orders = dbContext.Orders.Where(x => customers.Any(y => y.Id == x.CustomerId)).Include(x => x.someOtherTable).ToList();
For some reason this always results in an exception saying that the LINQ expression could not be translated.出于某种原因,这总是导致异常,指出无法翻译 LINQ 表达式。 My assumption is that this is due to the fact that the CustomerId in Order is nullable.我的假设是,这是因为 Order 中的 CustomerId 可以为空。 I am not sure though.我不确定。
Order :订购:
public int Id { get; set; }
public int? CustomerId { get; set; } // has to be nullable
...
Customer :客户:
public int Id { get; set; }
public string Name { get; set; } // has to be nullable
...
This is only a small snippet due to simplicity.由于简单,这只是一个小片段。
No, the reason is that customers
is IEnumerable
, not IQueryable
, so LINQ can not transale to SQL code your collection.不,原因是customers
是IEnumerable
,而不是IQueryable
,因此 LINQ 无法将您的集合转换为 SQL 代码。
Convert your IEnumerable<Customer>
to id list:将您的IEnumerable<Customer>
转换为 id 列表:
int[] ids = customers.Select(o => o.id).ToArray();
And Where
with Contains
:而Where
有Contains
:
List<Order> orders = dbContext.Orders.Where(x => ids.Contains(x.Id))
.Include(x => x.someOtherTable).ToList();
My issue was that I was using a read only property [x.Id] in the linq statement.我的问题是我在 linq 语句中使用了只读属性 [x.Id]。
In my partial class:在我的部分课程中:
public partial class Paddock
{
public int Id => EntityId;
}
My linq query with error:我的 linq 查询出错:
var paddocks = _context.Paddocks.Where(x => ids.Contains(x.Id)).ToList();
Changing it to the true property fixed it for me:将其更改为 true 属性为我修复了它:
var paddocks = _context.Paddocks.Where(x => ids.Contains(x.EntityId)).ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.