Skip to content

Instantly share code, notes, and snippets.

@phil-scott-78
Created May 4, 2016 01:16
Show Gist options
  • Save phil-scott-78/31a2dc7e9dd280442a40d0af417d3791 to your computer and use it in GitHub Desktop.
Save phil-scott-78/31a2dc7e9dd280442a40d0af417d3791 to your computer and use it in GitHub Desktop.
FastCount for SQL Server and EntityFramework
public static class QueryExtensions
{
public static long FastCount<TEntity>(this DbContext context) where TEntity : class
{
var name = context.GetTableName<TEntity>();
var sql =
$@"SELECT SUM (row_count)
FROM sys.dm_db_partition_stats
WHERE object_id=OBJECT_ID('{name}')
AND (index_id=0 or index_id=1);";
var results = context.Database.SqlQuery<long>(sql);
return results.First();
}
// table name query courtesy of http://stackoverflow.com/a/27216884/54342
public static string GetTableName<T>(this DbContext context) where T : class
{
var objectContext = ((IObjectContextAdapter)context).ObjectContext;
return objectContext.GetTableName(typeof(T));
}
public static string GetTableName(this DbContext context, Type t)
{
var objectContext = ((IObjectContextAdapter)context).ObjectContext;
return objectContext.GetTableName(t);
}
private static readonly ConcurrentDictionary<Type, string> TableNames = new ConcurrentDictionary<Type, string>();
public static string GetTableName(this ObjectContext context, Type t)
{
return TableNames.GetOrAdd(t, type =>
{
var storageMetadata = context.MetadataWorkspace.GetItems<EntityContainerMapping>(DataSpace.CSSpace);
var entityName = t.Name;
foreach (var ecm in storageMetadata)
{
EntitySet entitySet;
if (ecm.StoreEntityContainer.TryGetEntitySetByName(entityName, true, out entitySet))
{
return entitySet.Schema + "." + entitySet.Table;//TODO: brackets
}
}
return "";
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment