Cleve
Cleve

Reputation: 1433

How to get a list of database names from a SQL Server instance using Entity Framework?

I would like to use Entity Framework (EF) to query a SQL Server instance and return a list of database names on that instance.

I can do this using the following code, but wondered if there was a way with EF?

   public static string[] GetDatabaseNames(SqlConnection masterConn)
    {
        List<string> databases = new List<string>();

        //  retrieve the name of all the databases from the sysdatabases table
        using (SqlCommand cmd = new SqlCommand("SELECT [name] FROM sysdatabases", masterConn))
        {
            using (SqlDataReader rdr = cmd.ExecuteReader())
            {
                while (rdr.Read())
                {
                    databases.Add((string)rdr["name"]);
                }
            }
        }

        return databases.ToArray();
    }

I should mention that I am new to EF and its capabilities / limitations.

Upvotes: 3

Views: 3643

Answers (2)

Atlasmaybe
Atlasmaybe

Reputation: 1549

You could simply send a raw query to your SQL Server through Entity Framework :

using (var context = new MyContext()) 
{ 
    var dbNames = context.Database.SqlQuery<string>(
        "SELECT name FROM sys.databases").ToList(); 
}

Sources : https://msdn.microsoft.com/en-us/library/jj592907(v=vs.113).aspx and https://stackoverflow.com/a/147662/2699126

Upvotes: 8

Dakota
Dakota

Reputation: 525

You create view in SQL database

CREATE VIEW [dbo].[SysDatabasesView] AS SELECT * FROM sys.databases

then add this object into edmx

Upvotes: 1

Related Questions