如何首先获取 EF 6 数据库中的 Schama.TableName?

How to get the the Schama.TableName in EF 6 database-first?

我正在使用 EF 6 数据库优先.. 我使用此方法获取 table:

的名称
private static string GetTableName(ObjectContext context, Type entityType)
        {
            string entityTypeName = entityType.Name;

            EntityContainer container = context.MetadataWorkspace.GetEntityContainer(context.DefaultContainerName, DataSpace.CSpace);
            string tableName = (from meta in container.BaseEntitySets
                                where meta.ElementType.Name == entityTypeName
                                select meta.Name).First();
            return tableName;
        }

但它只是 return 的 table 名称,我在数据库中有 5 个模式,每个模式对应一个单独的 DbContext,因此它可能具有相同的名称但不同模式。所以我需要return全名table

基本上您需要 EntitySet class 的 TableSchema 属性。不幸的是,它们仅针对 storage 模型正确填充,因此为了找到它,您需要完成几个模型映射。

这是基于(实际上是一部分)Rowan Miller 的优秀 post EF6.1 Get Mapping Between Properties and Columns` 的示例方法:

static EntitySet GetStorageEntitySet(ObjectContext objectContext, Type clrEntityType)
{ 
    var metadata = 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) == clrEntityType);

    // 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
    return mapping
        .EntityTypeMappings.Single()
        .Fragments.Single()
        .StoreEntitySet;
}

您的示例用法:

private static string GetTableName(ObjectContext context, Type entityType)
{
    var entitySet = GetStorageEntitySet(context, entityType);
    return entitySet.Schema + "." + entitySet.Table;
}

更新:原来Code First和Database First在EntitySet TableName属性方面存在差异, 所以要获得 table 一般的名称,我建议使用:

var tableName = entitySet.Table ?? entitySet.Name;