Skip to content Skip to sidebar Skip to footer

How To Execute Raw Sql With In Statement Using Entity Framework 6

I have a list that contains some ID's, and I'd want to pick the records whose ID is in that list. So far I have var ids = new List {1, 2, 3}; // Actually the list is n

Solution 1:

I don't think you can pass array to sql, this works on SqlServer You might need to change to new MySQLParameter for MySql

var inParams = ids.Select((id, i) =>newSqlParameter("p"+i, id));

var query = "select * from Employees where Id in (" + string.Join(",", inParams.Select(p =>"@" + p.ParameterName)) + ")";

var data = db.Database.SqlQuery<Employee>(query, inParams.Cast<object>().ToArray()).ToList();

Also you can use LINQ for more complex queries as well ones that have AS and JOIN and UNION

Post a Comment for "How To Execute Raw Sql With In Statement Using Entity Framework 6"