Skip to content

Instantly share code, notes, and snippets.

@jwatney
Last active March 31, 2017 16:14
Show Gist options
  • Save jwatney/552276bc07dc630d7faabe87b450ee9c to your computer and use it in GitHub Desktop.
Save jwatney/552276bc07dc630d7faabe87b450ee9c to your computer and use it in GitHub Desktop.
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);
}
}
@jwatney
Copy link
Author

jwatney commented Mar 30, 2017

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.

@jwatney
Copy link
Author

jwatney commented Mar 31, 2017

Haha. Previous version blew on caching -- context was disposed. Here's the straight up version.

@jwatney
Copy link
Author

jwatney commented Mar 31, 2017

Added some methods for Dapper.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment