EF获取数据库表名和列名
EF获取数据库表名和列名
-
- /// <summary>
- /// 通过当前DBContext上下文获取对应数据库中所有得表
- /// </summary>
- /// <returns></returns>
- public List<string> GetTableNames()
- {
- var TableNames = new List<string>();
- var metadata = ((IObjectContextAdapter) this).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");
- 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();
- TableNames.Add(tableSchema + "." + tableName);
- }
- return TableNames;
- }
- public List<string> GetColumnNamesByTable(string tableName)
- {
- string name = tableName.Split('.')[1];
- string schema = tableName.Split('.')[0];
- var ColumnNames = new List<string>();
- var metadata = ((IObjectContextAdapter)this).ObjectContext.MetadataWorkspace;
- var table = metadata.GetItemCollection(DataSpace.SSpace).GetItems<EntityContainer>().Single().BaseEntitySets.OfType<EntitySet>().Where(s=>!s.MetadataProperties.Contains("Type") || s.MetadataProperties["Type"].ToString() == "Tables").FirstOrDefault(t => t.Table==name&&t.Schema==schema);
-
- foreach (var member in table.ElementType.Members)
- {
- var ColumnName = member.Name;
- ColumnNames.Add(ColumnName);
- }
- return ColumnNames;
- }
只要心中有梦,不管什么天气都适合睡觉