正如问题所述,任何人都知道如何在实体框架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 。您可以在此链接中找到更多信息

return this.Model.FindEntityType(type).SqlServer().TableName;


Related

许可下: CC-BY-SA with attribution
不隶属于 Stack Overflow
这个KB合法吗? 是的,了解原因
许可下: CC-BY-SA with attribution
不隶属于 Stack Overflow
这个KB合法吗? 是的,了解原因