Ale*_*dre 15 c# entity-framework-4.1
要在Entity framework 4.0上获取数据库表名,我会:
ObjectSetInstance.EntitySet.ToString()
Run Code Online (Sandbox Code Playgroud)
有没有办法在Entity Framework 4.1上执行此操作?
Rui*_*mba 24
DbContext和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;
}
}
Run Code Online (Sandbox Code Playgroud)
使用ObjectContext对象:
ObjectContext context = ....;
string table = context.GetTableName<Foo>();
Run Code Online (Sandbox Code Playgroud)
使用DbContext对象:
DbContext context = ....;
string table = context.GetTableName<Foo>();
Run Code Online (Sandbox Code Playgroud)
更多信息:
尝试这样的事情:
string name = (context as IObjectContextAdapter).ObjectContext.CreateObjectSet<MyClass>().EntitySet.Name;
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
19154 次 |
最近记录: |