获取实体表名称 - EF7

时间:2015-10-10 07:12:34

标签: c# .net entity-framework entity-framework-6 entity-framework-core

正如问题所述,任何人都知道如何在实体框架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;
}

1 个答案:

答案 0 :(得分:13)

你现在唯一需要做的就是: 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;