LINQ表达式无法翻译 [英] The LINQ expression could not be translated

查看:141
本文介绍了LINQ表达式无法翻译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 Orders 的表和一个名为 Customers 的列表. Orders 具有属性 CustomerId .现在,我要获取 Customers 列表中的所有客户订单.

I have a table called Orders and a list called Customers. Orders has a property CustomerId. Now I want to get all orders of customers that are in my Customers list.

这是我尝试过的:

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

由于某种原因,这总是会导致一个异常,说明无法翻译LINQ表达式.我的假设是,这是由于Order中的CustomerId可为空.我不确定.

For some reason this always results in an exception saying that the LINQ expression could not be translated. My assumption is that this is due to the fact that the CustomerId in Order is nullable. I am not sure though.

订单:

public int Id { get; set; }
public int? CustomerId { get; set; } // has to be nullable
...

客户:

public int Id { get; set; }
public string Name { get; set; } // has to be nullable
...

由于简单,这只是一小段.

This is only a small snippet due to simplicity.

推荐答案

不,原因是 customers IEnumerable ,而不是 IQueryable ,因此LINQ无法将您的收藏转换为SQL代码.

No, the reason is that customers is IEnumerable, not IQueryable, so LINQ can not transale to SQL code your collection.

将您的 IEnumerable< Customer> 转换为ID列表:

Convert your IEnumerable<Customer> to id list:

int[] ids = customers.Select(o => o.id).ToArray();

以及其中包含:

List<Order> orders = dbContext.Orders.Where(x => ids.Contains(x.Id))
                                     .Include(x => x.someOtherTable).ToList();

这篇关于LINQ表达式无法翻译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆