c# - 获取实体表名称 - EF7

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

正如问题所述,任何人都知道如何在 Entity Framework 7 中获取实体表名称?

我在 Entity Framework 6.1 中有执行此操作的代码(来自另一个站点,无法找到链接),但在 Entity Framework 7 中似乎没有引用任何接口(interface)/对象。

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。您可以在此 link 中找到更多信息

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

关于c# - 获取实体表名称 - EF7,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33051350/

相关文章:

c# - "System.Math.Cos"可以返回一个(float)吗?

.net - 在应用程序级别设置WPF DataGrid选中的行颜色

c# - 无法将时间类型 System.TimeSpan 隐式转换为 'long'

asp.net-mvc - 尝试将 DbSet<TEntity>.Where() 与 EF7 和 ASP.NET5 一起使用

c# - 为什么 Find 方法生成 TOP(2) 查询?

c# - 如何使用 C# 字典填充 docusign 模板?

c# - 如何在 C# 中获得不可空 T 以在函数中使用它?

c# - 跨平台日志记录

c# - 比较字符串是否相等

c# - 带正则表达式的匹配表