简体   繁体   English

将数组连接到EF查询

[英]Join array to EF query

I get the following error when trying to join an array to the Linq-to-EF query 尝试将数组连接到Linq-to-EF查询时出现以下错误

An error occurred while executing the command definition. 执行命令定义时发生错误。 See the inner exception for details. 有关详细信息,请参阅内部异常 Some part of your SQL statement is nested too deeply. SQL语句的某些部分嵌套得太深。 Rewrite the query or break it up into smaller queries. 重写查询或将其分解为较小的查询。

The code is as follows: 代码如下:

var vids = new List<string>();
using (var ctx = new MyDbContext())
{
    var qry = ctx.Pickups.Where(p => p.UserName == User.Identity.Name);
    if (someBoolean)
    {
        var v = GetVids(); // get the list of Ids from a web service
        vids.AddRange(v);
    }
    if (vids.Count() > 0)
    {
        qry = qry.Join(vids, p => p.VId, v => v, (v, p) => p);
    }
    var data = qry
        .Select(p => new
        {
            // etc.
        });
}

The problem is that the web service is not associated with the DB I'm using EF with, otherwise, I'd just do the join against the tables in the DB. 问题是Web服务与我使用EF的数据库没有关联,否则,我只是对数据库中的表进行连接。 The number of Id's I get back from the web service could be upwards of a hundred or so (usually 5-10). 我从网络服务中回来的Id的数量可能超过一百(通常是5-10)。 If I comment out the Join, the code works fine, so I know the error is in the Join. 如果我注释掉Join,代码工作正常,所以我知道错误在Join中。 With just a few (up to about 30) ids in vids, the join works perfectly. 只有少数(最多约30个)id中的id,连接工作完美。

What do you recommend to remedy this problem? 您建议如何解决此问题? The only thing I could think of was to insert the list of IDs into the DB and do the join that way. 我唯一能想到的是将ID列表插入数据库并以这种方式进行连接。 That doesn't seem too appealing to me. 这对我来说似乎不太吸引人。

Try to replace if (vids.Count() > 0) with: 尝试将if (vids.Count() > 0)替换为:

if (vids.Count > 0)
{
    qry = qry.Where(arg => vids.Contains(arg.VId));
}

This will work only if vids is less then 2100 elements, as this will be translated to IN (x, y, .., n) condition. 仅当vids小于2100个元素时才会起作用,因为这将转换为IN (x, y, .., n)条件。

If you use entity framework 3.5, then Contains will not work. 如果您使用实体框架3.5,则Contains将不起作用。 You can find possible solution here: 'Contains()' workaround using Linq to Entities? 你可以在这里找到可能的解决方案: 使用Linq to Entities的'Contains()'解决方法?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM