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

msh*_*hwf 1 c# entity-framework ef-database-first

我首先使用 EF 6 数据库。我使用这种方法来获取表的名称:

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;
        }
Run Code Online (Sandbox Code Playgroud)

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

Iva*_*oev 5

基本上你需要TableSchemaEntitySet类的属性。不幸的是,它们仅针对存储模型正确填充,因此为了找到它,您需要通过多个模型映射。

这是基于(实际上是)优秀帖子的示例方法 由 Rowan Miller撰写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;
}
Run Code Online (Sandbox Code Playgroud)

您的案例中的示例用法:

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

更新:原来,有关于代码优先和数据库优先之间的差异EntitySet TableName特性,所以要得到表名一般我会建议使用:

var tableName = entitySet.Table ?? entitySet.Name;
Run Code Online (Sandbox Code Playgroud)