开发者

Join array to EF query

I get the following error when trying to join an array to the Linq-to-EF query

An error occurred while executing the command definition. See the inner exception for details. Some part of your SQL statement is nested too deeply. 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. The number of Id's I get back from the web service could be upwards of a hundred or so (usually 5-10). If I comment out the Join, the code works fine, so I know the error is in the Join. With just a few (up to about 30) ids in vids, the join works perfectly.

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. That doesn't seem too appealing to me.


Try to replace if (vids.Count() > 0) with:

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.

If you use entity framework 3.5, then Contains will not work. You can find possible solution here: 'Contains()' workaround using Linq to Entities?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜