2

I want a list of tables that exists on sqlite database, and well I've got a simple query that looks like:

SELECT name from sqlite_master WHERE type='table';

But now I need to execute this using entity framework core, so I am binding this to DataContext, and here is where I am stuck as data context contains all representation of tables as db set but not sqlite system tables, I tried using query on exposed database facade but it is not returning any pother values then number of rows it has affected, something like:

using (var ctx = new DataContext())
{
    var query = @"SELECT name from sqlite_master WHERE type='table';"
    string[] result = ctx.Database.ExecuteSqlCommand(query);
    return result;
}

Is there any other way i can that information.

Wojciech Szabowicz
  • 3,646
  • 5
  • 43
  • 87

2 Answers2

6

You can directly use ADO.NET commands with EntityFrameworkCore

using (var ctx = new DataContext())
{
    using (var command = ctx.Database.GetDbConnection().CreateCommand())
    {
        command.CommandText = "SELECT name from sqlite_master WHERE type='table'";
        ctx.Database.OpenConnection();
        using (var result = command.ExecuteReader())
        {
            while (result.Read())
            {
                Console.WriteLine(result.GetString(0));
            }
        }
    }
}
jgoday
  • 2,768
  • 1
  • 18
  • 17
-2

In case you need a schema with a list of tables inside the database you can always do:

using (var ctx = new DataContext())
{
    DataTable dbSchemaWithTables = ctx.Database.GetDbConnection().GetSchema("Tables");
}
Ivan B
  • 84
  • 8