如何在实体框架中获取表的架构名称?

Luk*_*Lee 5 c# schema entity entity-framework

我使用 User-Schema Separation 技术来分隔数据库中的表。你能告诉我如何在实体框架中获取实体集(表)的架构名称吗?谢谢。

Rui*_*mba 2

DbContextObjectContext的扩展方法:

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)

更多信息请点击这里:

实体框架:从实体获取映射表名称