实体框架 - 从实体获取表名称

发布于 2024-11-09 12:13:29 字数 717 浏览 7 评论 0原文

我正在使用 Entity Framework 4.1 和 Code First 方法。我能够获取实体的存储模型类型和列名称:

var items = context.ObjectContext.MetadataWorkspace.GetItems<EntityType>(DataSpace.SSpace);

foreach (var i in items)
{
    Console.WriteLine("Table Name: {0}", i.Name);

    Console.WriteLine("Keys:");
    foreach (var key in i.KeyMembers)
        Console.WriteLine("\t{0} ({1})", key.Name, key.TypeUsage.EdmType.FullName);

    Console.WriteLine("Members:");
    foreach (var member in i.Members)
        Console.WriteLine("\t{0} ({1})", member.Name, member.TypeUsage.EdmType.FullName);
}

我需要的是获取实体映射到的真实表名称。有不同的方法来指定(通过使用 Fluent-API .ToTable()、DataAnnotation [TableAttribute])。

有什么通用的方法可以获取这些信息吗?

I'm using the Entity Framework 4.1 with Code First approach. I'm able to get the storage model types and column names of my entities:

var items = context.ObjectContext.MetadataWorkspace.GetItems<EntityType>(DataSpace.SSpace);

foreach (var i in items)
{
    Console.WriteLine("Table Name: {0}", i.Name);

    Console.WriteLine("Keys:");
    foreach (var key in i.KeyMembers)
        Console.WriteLine("\t{0} ({1})", key.Name, key.TypeUsage.EdmType.FullName);

    Console.WriteLine("Members:");
    foreach (var member in i.Members)
        Console.WriteLine("\t{0} ({1})", member.Name, member.TypeUsage.EdmType.FullName);
}

What I need is to get the real table name the entity is mapped to. There are different ways to specify that (by using Fluent-API .ToTable(), DataAnnotation [TableAttribute]).

Is there any common way to achieve this information?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

奈何桥上唱咆哮 2024-11-16 12:13:29

EF 6.1,代码优先:

public static string GetTableName<T>(this DbContext context) where T : class
{
    ObjectContext objectContext = ((IObjectContextAdapter)context).ObjectContext;
    return objectContext.GetTableName(typeof(T));
}

public static string GetTableName(this DbContext context, Type t)
{
    ObjectContext objectContext = ((IObjectContextAdapter)context).ObjectContext;
    return objectContext.GetTableName(t);
}

private static readonly Dictionary<Type,string> TableNames = new Dictionary<Type, string>();

public static string GetTableName(this ObjectContext context, Type t)
{
    string result;

    if (!TableNames.TryGetValue(t, out result))
    {
        lock (TableNames)
        {
            if (!TableNames.TryGetValue(t, out result))
            {

                string entityName = t.Name;

                ReadOnlyCollection<EntityContainerMapping> storageMetadata = context.MetadataWorkspace.GetItems<EntityContainerMapping>(DataSpace.CSSpace);

                foreach (EntityContainerMapping ecm in storageMetadata)
                {
                    EntitySet entitySet;
                    if (ecm.StoreEntityContainer.TryGetEntitySetByName(entityName, true, out entitySet))
                    {
                        result = entitySet.Schema + "." + entitySet.Table;//TODO: brackets
                        break;
                    }
                }

                TableNames.Add(t,result);
            }
        }
    }

    return result;
}

EF 6.1, code-first:

public static string GetTableName<T>(this DbContext context) where T : class
{
    ObjectContext objectContext = ((IObjectContextAdapter)context).ObjectContext;
    return objectContext.GetTableName(typeof(T));
}

public static string GetTableName(this DbContext context, Type t)
{
    ObjectContext objectContext = ((IObjectContextAdapter)context).ObjectContext;
    return objectContext.GetTableName(t);
}

private static readonly Dictionary<Type,string> TableNames = new Dictionary<Type, string>();

public static string GetTableName(this ObjectContext context, Type t)
{
    string result;

    if (!TableNames.TryGetValue(t, out result))
    {
        lock (TableNames)
        {
            if (!TableNames.TryGetValue(t, out result))
            {

                string entityName = t.Name;

                ReadOnlyCollection<EntityContainerMapping> storageMetadata = context.MetadataWorkspace.GetItems<EntityContainerMapping>(DataSpace.CSSpace);

                foreach (EntityContainerMapping ecm in storageMetadata)
                {
                    EntitySet entitySet;
                    if (ecm.StoreEntityContainer.TryGetEntitySetByName(entityName, true, out entitySet))
                    {
                        result = entitySet.Schema + "." + entitySet.Table;//TODO: brackets
                        break;
                    }
                }

                TableNames.Add(t,result);
            }
        }
    }

    return result;
}
此生挚爱伱 2024-11-16 12:13:29

我发现获取表名称的最简单方法如下:

var tables = Context.MetadataWorkspace.GetItems(System.Data.Metadata.Edm.DataSpace.CSpace)
                .Where(x => (x.MetadataProperties.Contains("NamespaceName") ? String.Compare(x.MetadataProperties["NamespaceName"].Value.ToString(), "Model", true) == 0 : false)
                && !x.MetadataProperties.Contains("IsForeignKey")
                && x.MetadataProperties.Contains("KeyMembers"));

这将为您提供表实体。

然后,您可以执行以下操作来提取名称:

            foreach (var item in tables)
            {
                EntityType itemType = (EntityType)item;
                String TableName = itemType.Name;
            }

请注意,如果您对上下文进行复数化,则需要撤消该操作。

The Easiest way I have found to get table names is the following:

var tables = Context.MetadataWorkspace.GetItems(System.Data.Metadata.Edm.DataSpace.CSpace)
                .Where(x => (x.MetadataProperties.Contains("NamespaceName") ? String.Compare(x.MetadataProperties["NamespaceName"].Value.ToString(), "Model", true) == 0 : false)
                && !x.MetadataProperties.Contains("IsForeignKey")
                && x.MetadataProperties.Contains("KeyMembers"));

That will get you the table entities.

Then you can do the following to extract the name:

            foreach (var item in tables)
            {
                EntityType itemType = (EntityType)item;
                String TableName = itemType.Name;
            }

Note if your pluralizing the context you will need to undo that.

秋心╮凉 2024-11-16 12:13:29

还有另一种方法可以获取 EDM 表名称

  public static string GetTableName<T>(this ObjectContext context) where T : EntityObject
    {
        var entities= context.MetadataWorkspace.GetItems(System.Data.Metadata.Edm.DataSpace.CSpace).Where(b => b.BuiltInTypeKind == BuiltInTypeKind.EntityType);

        foreach (System.Data.Metadata.Edm.EntityType item in entities)
        {
            if(item.FullName==typeof(T).FullName)
                return item.Name;
        }

        return String.Empty;
    }

There is an other way you can get the EDM Table Name

  public static string GetTableName<T>(this ObjectContext context) where T : EntityObject
    {
        var entities= context.MetadataWorkspace.GetItems(System.Data.Metadata.Edm.DataSpace.CSpace).Where(b => b.BuiltInTypeKind == BuiltInTypeKind.EntityType);

        foreach (System.Data.Metadata.Edm.EntityType item in entities)
        {
            if(item.FullName==typeof(T).FullName)
                return item.Name;
        }

        return String.Empty;
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文