SQL “not in” syntax for Entity Framework 4.1

会有一股神秘感。 提交于 2019-11-28 22:54:16

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...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!