EF获取数据库表名和列名

EF获取数据库表名和列名

  1.  
  2. /// <summary> 
  3. /// 通过当前DBContext上下文获取对应数据库中所有得表 
  4. /// </summary> 
  5. /// <returns></returns> 
  6. public List<string> GetTableNames() 

  7. var TableNames = new List<string>(); 
  8. var metadata = ((IObjectContextAdapter) this).ObjectContext.MetadataWorkspace; 
  9. var tables = metadata.GetItemCollection(DataSpace.SSpace).GetItems<EntityContainer>().Single() 
  10. .BaseEntitySets.OfType<EntitySet>() 
  11. .Where(s => !s.MetadataProperties.Contains("Type") || 
  12. s.MetadataProperties["Type"].ToString() == "Tables"); 
  13. foreach (var table in tables) 

  14. var tableName = table.MetadataProperties.Contains("Table") && 
  15. table.MetadataProperties["Table"].Value != null 
  16. ? table.MetadataProperties["Table"].Value.ToString() 
  17. : table.Name; 
  18. var tableSchema = table.MetadataProperties["Schema"].Value.ToString(); 
  19. TableNames.Add(tableSchema + "." + tableName); 

  20. return TableNames; 

  21. public List<string> GetColumnNamesByTable(string tableName) 

  22. string name = tableName.Split('.')[1]; 
  23. string schema = tableName.Split('.')[0]; 
  24. var ColumnNames = new List<string>(); 
  25. var metadata = ((IObjectContextAdapter)this).ObjectContext.MetadataWorkspace; 
  26. 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); 
  27.  
  28. foreach (var member in table.ElementType.Members) 

  29. var ColumnName = member.Name; 
  30. ColumnNames.Add(ColumnName); 

  31. return ColumnNames; 

posted @ 2017-07-13 10:33  明明.如月  阅读(3692)  评论(0编辑  收藏  举报