0

I am using MySQL and I need to loop through all the names of the schemas in MySQL and then return back as an array to allow me to loop through the names. How do I achieve this using 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?

If Linq does not have this ability, is there a way to achieve this using .SqlQuery() method?

1

1 Answer 1

1

It's not possible to do with LINQ. But you can try passing raw SQL string

"SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA"

UPDATE

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

This should work.

Sign up to request clarification or add additional context in comments.

1 Comment

Can you please give me the full code. I keep getting error messages in mine. I have typed the below var dbNames = serverDataContext.Database.FromSqlRaw("SELECT name FROM master.dbo.sysdatabases").ToList(); but it says it does not contain a definition for 'FromSqlRaw'

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.