SQL “not in” syntax for Entity Framework 4.1

前端 未结 4 2007
别跟我提以往
别跟我提以往 2020-12-15 04:32

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

相关标签:
4条回答
  • 2020-12-15 04:55

    Try this for starters ...

    m => !listIDs.Contains(m.ID)
    
    0 讨论(0)
  • 2020-12-15 04:59

    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.

    0 讨论(0)
  • 2020-12-15 05:01

    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);
    
    0 讨论(0)
  • 2020-12-15 05:05

    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 讨论(0)
提交回复
热议问题