开发者

SQL "not in" syntax for Entity Framework 4.1

I have a simple issue with Entity Framework syntax for the "not in" SQL equivalent. Essentially, I want to convert the following SQL syntax into Entity Framework syntax:

select  ID
from    dbo.List
where   ID not in (list of IDs)

Here is a method that I use for looking up a single record:

public static List GetLists(int id)
{
    using (dbInstance db = new dbInstance())
    {
        return db.Lists.Where(m => m.ID == id);
    }
}

Here is a pseudo-method that I want to use for this:

public static List<List> GetLists(List<int> listIDs)
{
    using (dbInstance db = new dbInstance())
    {
        return db.Lists.Where(**** What Goes Here ****).ToList();
    }
}

Can anyone give me pointers as to what goes in t开发者_StackOverflow社区he Where clause area? I read some forums about this and saw mention of using .Contains() or .Any(), but none of the examples were a close enough fit.


Give this a go...

public static List<List> GetLists(List<int> listIDs)
{
    using (dbInstance db = new dbInstance())
    {
        // Use this one to return List where IS NOT IN the provided listIDs
        return db.Lists.Where(x => !listIDs.Contains(x.ID)).ToList();

        // Or use this one to return List where IS IN the provided listIDs
        return db.Lists.Where(x => listIDs.Contains(x.ID)).ToList();
    }
}

These will turn into approximately the following database queries:

SELECT [Extent1].*
FROM [dbo].[List] AS [Extent1]
WHERE  NOT ([Extent1].[ID] IN (<your,list,of,ids>))

or

SELECT [Extent1].*
FROM [dbo].[List] AS [Extent1]
WHERE  [Extent1].[ID] IN (<your,list,of,ids>)

respectively.


This one requires you to think backwards a little bit. Instead of asking if the value is not in some list of ids, you have to ask of some list of id's does not contain the value. Like this

int[] list = new int[] {1,2,3}
Result = (from x in dbo.List where list.Contains(x.id) == false select x);


Try this for starters ...

m => !listIDs.Contains(m.ID)


This might be a way to do what you want:

// From the method you provided, with changes...
public static List GetLists(int[] ids) // Could be List<int> or other =)
{
    using (dbInstance db = new dbInstance())
    {
        return db.Lists.Where(m => !ids.Contains(m.ID));
    }
}

However I've found that doing so might raise error on some scenarios, specially when the list is too big and connection is somewhat slow.

Remember to check everything else BEFORE so this filter might have less values to check.

Also remember that Linq does not populate the variable when you build your filter/query (at least not by default). If you're going to iterate for each record, remember to call a ToList() or ToArray() method before, unless each record has 500MB or more...

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜