Skip to content

Instantly share code, notes, and snippets.

@pmunin
Last active January 21, 2016 20:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pmunin/0733f3bffa24ad2257ac to your computer and use it in GitHub Desktop.
Save pmunin/0733f3bffa24ad2257ac to your computer and use it in GitHub Desktop.
DbContextQueryExtension allows to query data from DbContext (EntityFramework 5+)
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.Entity;
using System.Data.Entity.Core.Objects;
using System.Data.Entity.Infrastructure;
using System.Linq;
/// <summary>
/// DbContextQueryExtension allows to query data from DbContext (EntityFramework 5+)
/// Latest version is here: https://gist.github.com/pmunin/0733f3bffa24ad2257ac
/// </summary>
public static class DbContextQueryExtensions
{
/// <summary>
/// Generates ObjectQuery as described here https://msdn.microsoft.com/library/bb738512(v=vs.100).aspx
/// </summary>
/// <param name="context"></param>
/// <param name="efQuery">EntityFramework SQL (not native)</param>
/// <returns></returns>
public static ObjectQuery<DbDataRecord> ObjectQuery(this DbContext context, string efQuery)
{
var oc = (context as IObjectContextAdapter).ObjectContext;
var queryStr = efQuery;
return new ObjectQuery<DbDataRecord>(queryStr, oc);
}
/// <summary>
/// Generates ObjectQuery of DbDataRecord and translates it to any object (including anonymous)
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="context"></param>
/// <param name="efQuery">EntityFramework SQL (not native)</param>
/// <param name="selector"></param>
/// <returns></returns>
public static IEnumerable<T> ObjectQuery<T>(this DbContext context, string efQuery, Func<DbDataRecord, T> selector)
{
var q = ObjectQuery(context, efQuery);
return q.Select(selector);
}
/// <summary>
/// Executes native SQL query on connection and translates results using specified delegate
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="context"></param>
/// <param name="sqlQuery">native sql query for DbCommand</param>
/// <param name="selector">defines translation of DataReader object to target object</param>
/// <returns></returns>
public static IEnumerable<T> SqlQuery<T>(this DbContext context, string sqlQuery, Func<DbDataReader, T> selector)
{
using (var cmd = context.Database.Connection.CreateCommand())
{
cmd.CommandText = sqlQuery;
var state = cmd.Connection.State;
cmd.Connection.Open();
try
{
cmd.CommandType = CommandType.Text;
using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess))
while (reader.Read())
{
yield return selector(reader);
}
}
finally
{
if (state == ConnectionState.Closed)
cmd.Connection.Close();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment