Last active
March 31, 2017 16:14
-
-
Save jwatney/552276bc07dc630d7faabe87b450ee9c to your computer and use it in GitHub Desktop.
This file contains hidden or 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; | |
using System.Collections.Generic; | |
using System.Data; | |
using System.Linq; | |
using System.Reflection; | |
using Dapper; | |
using Microsoft.EntityFrameworkCore; | |
public static class DbContextExtensions { | |
public static IQueryable<object> Set(this DbContext context, Type type) { | |
return (IQueryable<object>)context.GetType().GetMethod("Set").MakeGenericMethod(type).Invoke(context, null); | |
} | |
public static IEnumerable<T> Query<T>(this DbContext context, string sql, object param = null, IDbTransaction transaction = null, bool buffered = true, int? commandTimeout = null, CommandType ? commandType = null) { | |
return context.Database.GetDbConnection().Query<T>(sql, param, transaction, buffered, commandTimeout, commandType); | |
} | |
public static IEnumerable<dynamic> Query(this DbContext context, string sql, object param = null, IDbTransaction transaction = null, bool buffered = true, int? commandTimeout = null, CommandType? commandType = null) { | |
return context.Database.GetDbConnection().Query(sql, param, transaction, buffered, commandTimeout, commandType); | |
} | |
} |
Haha. Previous version blew on caching -- context was disposed. Here's the straight up version.
Added some methods for Dapper.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
An extension method for getting DbSet results using a non-generic method, e.g. context.Set(typeof(Foo)). Should be just about as fast as a DbSet() call after the first usage for T.