Extension methods for DbContext and ObjectContext:
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 (?<table>.*) AS");
Match match = regex.Match(sql);
string table = match.Groups["table"].Value;
return table;
}
}
Using a ObjectContext object:
ObjectContext context = ....;
string table = context.GetTableName<Foo>();
Using a DbContext object:
DbContext context = ....;
string table = context.GetTableName<Foo>();
More info here:
Entity Framework: Get mapped table name from an entity
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…