How to use parameters in Entity Framework in a “in” clause?

前端 未结 1 967
眼角桃花
眼角桃花 2021-01-18 22:23

I am using Entity Framework 4.0 and I want to use the following query:

To do that I do the following:

strSQLQuery = \"select * from MyTable where IDD         


        
相关标签:
1条回答
  • 2021-01-18 22:46

    There are a few problems with your code.

    First off, to fix your data type error, you'd have to convert strIDs to integers before doing anything else. This should work

    var ids = strIDs.Select(s => long.Parse(s));
    

    Now, since you're using entity framework already, why not use Linq instead of creating a SQL query?

    var results =
        from r in myContext.MyTable
        where ids.Contains(r.IDData)
        select r;
    

    Or in fluent syntax

    var results = myContext.MyTable.Where(r => strIDs.Contains(r.IDData));
    

    But if you really want to use SQL, the IN operator does not support parameters like that. You'd have to write it like this:

    strSQLQuery = "select * from MyTable where IDData IN(@ID1, @ID2, @ID3, ...)";
    

    So to do this without too much effort, you can generate your query from ids like this:

    strSQLQuery = "select * from MyTable where IDData IN(" + String.Join(", ", ids.Select((s, i) => "@ID" + i)) + ")";
    foreach(var parameter in ids.Select((s, i) => new SqlParameter("@ID" + i, s)))
    {
        lstParametros.Add(parameter);
    }
    
    0 讨论(0)
提交回复
热议问题