【问题标题】:Use C# LINQ to return back all database names使用 C# LINQ 返回所有数据库名称
【发布时间】:2021-09-03 09:12:25
【问题描述】:

我正在使用 MySQL,我需要遍历 MySQL 中所有模式的名称,然后作为数组返回以允许我遍历名称。如何使用 LINQ 实现这一目标?

var optionsBuilderForServerData = new DbContextOptionsBuilder<DataContext>()
   .UseMySql("server=localhost; user=user; password=password", 
   new MySqlServerVersion(new Version(8, 0, 21)));  

DataContext serverDataContext = new DataContext(optionsBuilderForServerData.Options);


var databaseNames = serverDataContext.  // what do I type here to view all database names?

如果Linq没有这个能力,有没有办法使用.SqlQuery()方法来实现?

【问题讨论】:

标签: c# asp.net .net linq asp.net-core


【解决方案1】:

不能使用 LINQ。但是你可以尝试传递原始 SQL 字符串

"SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA"

更新

List<string> results = new List<string>();
using (var command =context.Database.GetDbConnection().CreateCommand())
{
     context.Database.OpenConnection();
     command.CommandText = "SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA";
     using (var reader = command.ExecuteReader())
     {
          while (reader.Read())
          {
               results.Add(reader.GetString(0));
          }
     }
}

这应该可行。

【讨论】:

  • 你能给我完整的代码吗?我不断收到错误消息。我输入了以下 var dbNames = serverDataContext.Database.FromSqlRaw("SELECT name FROM master.dbo.sysdatabases").ToList();但它说它不包含“FromSqlRaw”的定义
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-22
  • 1970-01-01
  • 2018-07-17
  • 2017-03-11
  • 2017-06-01
  • 1970-01-01
相关资源
最近更新 更多