LINQ查询列出实体框架中的所有表
问题描述:
I want a LINQ query to work with Entity Framework to List All the Tables in Datamodel.
i.e. Same as "Select * from SysObjects where xtype='U' " in SQL Server
or "Select * from tab" in Oracle.
答
我得到了解决方案,但我找到了它没有实时帮助,因为它不是动态的,我使用Reflection得到另一个解决方案。
在这里我发现所有类型的当前正在执行的程序集,所以,我有手动删除Program和TestDBEntities。
Hi,
I got a solution about this, but I found it less helpful in real time because it is not dynamic, I got another solution using Reflection.
In this I m finding all types of currently executing Assembly so, I have to manually remove Program and TestDBEntities.
using System;
using System.Reflection;
namespace RetrievingORMTablesUsingReflection
{
class Program
{
TestDBEntities DbOrm = new TestDBEntities();
static void Main(string[] args)
{
Assembly A = Assembly.Load(Assembly.GetExecutingAssembly().FullName);
Type[] Types = A.GetTypes();
foreach (Type T in Types)
{
if (T.Name != "Program" && T.Name != "TestDBEntities")
Console.WriteLine(T.Name);
}
Console.Read();
}
}
}
列出实体的最佳方式可能是这样的:
The probably best way to list out entities is probably like this:
private void PopulateTableNames()
{
List<string> listOfTables= new List<string>();
tabeller.Clear();
var metadata = ((IObjectContextAdapter)db).ObjectContext.MetadataWorkspace;
var tables = metadata.GetItemCollection(DataSpace.SSpace)
.GetItems<EntityContainer>()
.Single()
.BaseEntitySets
.OfType<EntitySet>()
.Where(s => !s.MetadataProperties.Contains("Type")
|| s.MetadataProperties["Type"].ToString() == "Tables");
var PropertiesInTables = tables.Select(s => s.ElementType.Properties).ToList();
foreach (var table in tables)
{
var tableName = table.MetadataProperties.Contains("Table")
&& table.MetadataProperties["Table"].Value != null
? table.MetadataProperties["Table"].Value.ToString()
: table.Name;
var tableSchema = table.MetadataProperties["Schema"].Value.ToString();
listOfTables.Add(tableName);
}
}
请注意以上代码示例中的这一行:
Attention should also go to this line in the code sample above:
var PropertiesInTables = tables.Select(s => s.ElementType.Properties).ToList();
此Linq查询还为您提供每个表的字段(属性)。
[来自romiller.com]
This Linq query also gives you the fields (properties) of each table.
[From romiller.com]
查看此链接,有一种简单的方法:
Linq to Sql,sys tables
Check this link, there is an easy way:
Linq to Sql, sys tables