獲取實體表名稱 - EF7


正如問題所述,任何人都知道如何在實體框架7中獲取實體表名稱?

我有在實體框架6.1中執行此操作的代碼(來自另一個站點,無法找到鏈接),但實體框架7中似乎沒有引用任何接口/對象。

EF6.1的代碼

public string GetTableName(Type type)
{
    var metadata = ((IObjectContextAdapter)this).ObjectContext.MetadataWorkspace;
    var objectItemCollection = ((ObjectItemCollection)metadata.GetItemCollection(DataSpace.OSpace));
    var entityType = metadata.GetItems<EntityType>(DataSpace.OSpace).Single(e => objectItemCollection.GetClrType(e) == type);
    var entitySet = metadata.GetItems(DataSpace.CSpace).Where(x => x.BuiltInTypeKind == BuiltInTypeKind.EntityType).Cast<EntityType>().Single(x => x.Name == entityType.Name);
    var entitySetMappings = metadata.GetItems<EntityContainerMapping>(DataSpace.CSSpace).Single().EntitySetMappings.ToList();

    EntitySet table = null;

    var mapping = entitySetMappings.SingleOrDefault(x => x.EntitySet.Name == entitySet.Name);
    if (mapping != null)
    {
        table = mapping.EntityTypeMappings.Single().Fragments.Single().StoreEntitySet;
    }
    else
    {
        mapping = entitySetMappings.SingleOrDefault(x => x.EntityTypeMappings.Where(y => y.EntityType != null).Any(y => y.EntityType.Name == entitySet.Name));

        if (mapping != null)
        {
            table = mapping.EntityTypeMappings.Where(x => x.EntityType != null).Single(x => x.EntityType.Name == entityType.Name).Fragments.Single().StoreEntitySet;
        }
        else
        {
            var entitySetMapping = entitySetMappings.Single(x => x.EntityTypeMappings.Any(y => y.IsOfEntityTypes.Any(z => z.Name == entitySet.Name)));
            table = entitySetMapping.EntityTypeMappings.First(x => x.IsOfEntityTypes.Any(y => y.Name == entitySet.Name)).Fragments.Single().StoreEntitySet;
        }
    }

    return (string)table.MetadataProperties["Table"].Value ?? table.Name;
}

一般承認的答案

你現在唯一需要做的就是這樣做:

public string GetTableName(Type type)
{
   return this.Model.GetEntityType(type).SqlServer().TableName;
}

PS:我假設這個方法在你的DbContext類中聲明,否則為你的DbContext實例更改this關鍵字。

更新

GetEntityType已重命名為FindEntityType 。您可以在此鏈接中找到更多信息

public string GetTableName(Type type)
{
   return this.Model.GetEntityType(type).SqlServer().TableName;
}




許可下: CC-BY-SA
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因