从实体框架MetaData获取数据库表名称 [英] Get Database Table Name from Entity Framework MetaData
问题描述
我试图找出一种获取给定实体类型的底层SQL表名称的方法。我已经尝试了MetadataWorkspace查询,而我可以从对象或存储空间获取大量信息,我似乎无法弄清楚两者之间的映射方式。
所以说我有一个名为Lookup的对象模型中的类型 - 如何在数据库中找到tablename(wws_lookups)?
我可以查询所有用于CSpace和SSpace的EntityType对象,我可以看到这两个列表正确列出,但我无法弄清楚如何从CSpace获取SSpace。
有没有办法
我使用Nigel的方法(从提取表名.ToTraceString()
),但有一些修改,因为如果表不在默认SQL Server架构( dbo。{table-name}
)中,他的代码将无法工作。 / p>
我已经为 DbContext
和 ObjectContext
对象:
public static class Conte xtExtensions
{
public static string GetTableName&T;(此DbContext上下文)其中T:class
{
ObjectContext objectContext =((IObjectContextAdapter)context).ObjectContext;
return objectContext.GetTableName< T>();
}
public static string GetTableName< T>(此ObjectContext上下文)其中T:class
{
string sql = context.CreateObjectSet< T>()。 ToTraceString();
Regex regex = new Regex(@FROM\s +(?< table>。+)\s + AS);
匹配match = regex.Match(sql);
string table = match.Groups [table]。
返回表;
}
}
更多细节在这里:
实体框架:从实体获取映射表名称
I'm trying to figure out a way to get the underlying SQL table name for a given entity type. I've experimented around with the MetadataWorkspace queries and while I can get lots of information from the object or the storage space, I can't seem to figure out how to map between the two.
So say I have a type in the object model called Lookup - how do I find the tablename (wws_lookups) in the database?
I can query all the EntityType objects for CSpace and SSpace and I can see both listed correctly but I can't figure out how to get SSpace from CSpace.
Is there any way to do this?
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
这篇关于从实体框架MetaData获取数据库表名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!