c# - 如何在 Entity Framework 中获取表的架构名称?

标签 c# entity-framework schema entity

我使用用户模式分离技术来分离数据库中的表。你能告诉我如何在 Entity Framework 中获取 EntitySets(表)的架构名称吗?谢谢。

最佳答案

这现在一定是一个老话题了,但是对于那些仍然潜伏在 EF6+ 中(而不是 EF 核心)的人来说,基于同样优秀的博客 post过去的罗文·米勒 (Rowan Miller),请查看我用于显示有关给定实体的一些元信息的方法

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

关于c# - 如何在 Entity Framework 中获取表的架构名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8770158/

相关文章:

c# - 每当更新派生类时配置基类属性的自动更新 EF Core 2.0

c# - EF DbSet.Find 抛出 InvalidOperationException

mysql - 不同教授和类(class)的 SQL 查询

database - 需要有关对处理民意调查响应的数据库进行非规范化的建议

c# - 什么时候创建和分发 "reference assemblies"?

c# - 一对多关系的 INSERT 语句

c# - MSBuild - XPath - XmlPeek 可以读取但 XmlPoke 不能写入

数据网格中的 Wpf 绑定(bind)错误仍然显示值

用户的 Django 模型,例如,类似页面的情况

c# - 数组作为参数传递?