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

时间:2012-01-07 13:51:24

标签: c# entity-framework schema entity

我使用User-Schema Separation技术来分离数据库中的表。你能告诉我如何在Entity Framework中获取EntitySets(Tables)的Schema名称吗?感谢。

6 个答案:

答案 0 :(得分:2)

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;
    }
}

使用ObjectContext对象:

ObjectContext context = ....;
string table = context.GetTableName<Foo>();

使用DbContext对象:

DbContext context = ....;
string table = context.GetTableName<Foo>();

更多信息:

Entity Framework: Get mapped table name from an entity

答案 1 :(得分:2)

我找到了以下博客条目,解释了如何从元数据工作空间获取该信息:

https://romiller.com/2014/04/08/ef6-1-mapping-between-types-tables/

这是魔术的功能:

public static string GetTableName(Type type, DbContext context)
{
    var metadata = ((IObjectContextAdapter)context).ObjectContext.MetadataWorkspace;

    // Get the part of the model that contains info about the actual CLR types
    var objectItemCollection = ((ObjectItemCollection)metadata.GetItemCollection(DataSpace.OSpace));

    // Get the entity type from the model that maps to the CLR type
    var entityType = metadata
            .GetItems<EntityType>(DataSpace.OSpace)
            .Single(e => objectItemCollection.GetClrType(e) == type);

    // Get the entity set that uses this entity type
    var entitySet = metadata
        .GetItems<EntityContainer>(DataSpace.CSpace)
        .Single()
        .EntitySets
        .Single(s => s.ElementType.Name == entityType.Name);

    // Find the mapping between conceptual and storage model for this entity set
    var mapping = metadata.GetItems<EntityContainerMapping>(DataSpace.CSSpace)
            .Single()
            .EntitySetMappings
            .Single(s => s.EntitySet == entitySet);

    // Find the storage entity set (table) that the entity is mapped
    var table = mapping
        .EntityTypeMappings.Single()
        .Fragments.Single()
        .StoreEntitySet;

    // Return the table name from the storage entity set
    return (string)table.MetadataProperties["Table"].Value ?? table.Name;
}

答案 2 :(得分:1)

这一定是一个古老的主题,但对于那些仍然潜伏着EF6 +的人(如不是EF核心),基于时代后期Rowan Miller的同一优秀博客post,请检查我的用于显示关于给定实体的一些元信息的方法

public class DbTableMeta
{
    public string Schema { get; set; }

    public string Name { get; set; }

    public IEnumerable<string> Keys { get; set; }
}


public static DbTableMeta Meta(this DbContext context, Type type)
{
    var metadata = ((IObjectContextAdapter) context).ObjectContext.MetadataWorkspace;

    // Get the part of the model that contains info about the actual CLR types
    var items = (ObjectItemCollection) metadata.GetItemCollection(DataSpace.OSpace);

    // Get the entity type from the model that maps to the CLR type
    var entityType = metadata
        .GetItems<EntityType>(DataSpace.OSpace)
        .Single(p => items.GetClrType(p) == type);

    // Get the entity set that uses this entity type
    var entitySet = metadata
        .GetItems<EntityContainer>(DataSpace.CSpace)
        .Single()
        .EntitySets
        .Single(p => p.ElementType.Name == entityType.Name);

    // Find the mapping between conceptual and storage model for this entity set
    var mapping = metadata.GetItems<EntityContainerMapping>(DataSpace.CSSpace)
        .Single()
        .EntitySetMappings
        .Single(p => p.EntitySet == entitySet);

    // Find the storage entity set (table) that the entity is mapped
    var table = mapping
        .EntityTypeMappings.Single()
        .Fragments.Single()
        .StoreEntitySet;

    return new DbTableMeta
    {
        Schema = (string) table.MetadataProperties["Schema"].Value ?? table.Schema,
        Name = (string) table.MetadataProperties["Table"].Value ?? table.Name,
        Keys = entityType.KeyMembers.Select(p => p.Name),
    };
}

答案 3 :(得分:0)

对于使用代码优先的用户,架构名称在您的上下文的OnModelCreating覆盖中设置;

public static readonly string DefaultSchemaName = "Entities";

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.HasDefaultSchema(DefaultSchemaName);

    ...

因此,您应该可以从代码中的其他位置引用DefaultSchemaName

如果您没有首先构建模型上下文和EF填充,那么这个答案就不那么明显了。

答案 4 :(得分:0)

用于截断需要表名和模式的表的示例。

LocalStorage().getBrightness();

答案 5 :(得分:-3)

使用Entity Framework 6.1.3,您可以通过以下方式查询方案和表名:

  string tableNameWithScheme = context.Db<T>().Schema+"."+context.Db<T>().TableName;

其中T是您的实体和上下文的类型,是派生的System.Data.Entity.DBContext的实例。