Google+ Peter Bromberg's .NET Blog | ENTITY FRAMEWORK

Peter Bromberg's .NET Blog All Things Programming

How to Execute Generic Type SQL with Entity Framework

2. June 2014 11:28 by admin in ENTITY FRAMEWORK

public static T ExecuteSql<T>(DbContext ctx, string sql, List<DbParameter> parms)


DbCommand cmd = ctx.Database.Connection.CreateCommand();

cmd.CommandText = sql; cmd.CommandType = CommandType.Text;

foreach (DbParameter p in parms) cmd.Parameters.Add(p);

try {


DbDataReader reader = cmd.ExecuteReader();

ObjectResult<T> jInfo = ((IObjectContextAdapter) ctx) .ObjectContext .Translate<T>(reader);

return jInfo.FirstOrDefault();


finally { ctx.Database.Connection.Close();