实体框架 - 从实体获取表名 [英] Entity Framework - Get Table name from the Entity

查看:232
本文介绍了实体框架 - 从实体获取表名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用实体框架4.1 code第一种方法。我能够得到的存储模型类型和列名我的实体:

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);
}

我需要的是让实体映射到真正的表名。有不同的方式来指定(通过使用流利的-API .ToTable(),DataAnnotation [TableAttribute])。

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?

推荐答案

我已经找到了获得表名的最简单方法如下:

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"));

这将让你的表实体。

然后,你可以做以下提取名称:

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.

这篇关于实体框架 - 从实体获取表名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆