Created
January 3, 2019 08:30
-
-
Save joe-oli/5abe1d24d3d7cee4a9617ba11dd95cdd to your computer and use it in GitHub Desktop.
executing SELECT field1,field2 from Tablename WHERE pk IN (1,3,5,69) using EntityFramework
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections.Generic; //List<> | |
using System.Data.Entity.Infrastructure; //DbRawSqlQuery | |
using System.Data.SqlClient; //SqlParameter | |
using MyNamespace.EFLayer.MyModel; //EFEntities | |
/* executing SELECT field1,field2 from Tablename WHERE pk IN (1,3,5,69) using EntityFramework; | |
---------- | |
place the WHERE clause set in an array, e.g. wherePkeysArray = [1,3,5,69] | |
create a concrete class DTO.ResultObj such that its prop names match exactly the fields in your sql, i.e. field1, field2 | |
*/ | |
//SqlCommand cmd = new SqlCommand(); //dont use it's part of ADO.NET, we are using EF | |
List<SqlParameter> sqlParams = new List<SqlParameter>(); | |
//build the params string... e.g. "@p1, @p2, @p3"; | |
var paramsArr = new string[wherePkeysArray.Length]; //create as many params as there are values | |
for (int i = 0; i < wherePkeysArray.Length; i++) | |
{ | |
paramsArr[i] = string.Format("@p{0}", i); | |
//cmd.Parameters.AddWithValue(paramsArr[i], wherePkeysArray[i]); //@p0=123, @p1=456 cmdParameters is an SqlParameterCollection; we want an SqlParam Array !! | |
sqlParams.Add(new SqlParameter(paramsArr[i], wherePkeysArray[i])); | |
} | |
string sqlParameterized = string.Format(@" | |
SELECT field1, field2 FROM MyTable | |
WHERE pk IN ( {0} ) | |
", string.Join(", ", paramsArr)); | |
sqlParameterized = sqlParameterized.Replace(Environment.NewLine, ""); //clean Sql, remove all \r\n occurrences, not that it affects anything | |
sqlParameterized = sqlParameterized.Trim(); | |
//=> SELECT field1, field2 FROM MyTable WHERE pk IN ( @p1, @p2, @p3, @p4 ) | |
List<DTO.ResultObj> lst = null; | |
using (EFEntities dbCtx = new EFEntities()) | |
{ | |
DbRawSqlQuery<DTO.ResultObj> query = dbCtx.Database.SqlQuery<DTO.ResultObj>(sqlParameterized, sqlParams.ToArray()); | |
lst = query.ToList(); | |
} | |
return lst; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment