I use Nigel’s approach (extracting table name from .ToTraceString()
) but with some modifications, because his code won’t work if the table is not in the default SQL Server schema (dbo.{table-name}
).
I’ve created extension methods for DbContext
and ObjectContext
objects:
public static class ContextExtensions
{
public static string GetTableName<T>(this DbContext context) where T : class
{
ObjectContext objectContext = ((IObjectContextAdapter) context).ObjectContext;
return objectContext.GetTableName<T>();
}
public static string GetTableName<T>(this ObjectContext context) where T : class
{
string sql = context.CreateObjectSet<T>().ToTraceString();
Regex regex = new Regex(@"FROM\s+(?<table>.+)\s+AS");
Match match = regex.Match(sql);
string table = match.Groups["table"].Value;
return table;
}
}
More details here:
Entity Framework: Get mapped table name from an entity