3

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.

2 Answers 2

8

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

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

Comments

1

You create view in SQL database

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

then add this object into edmx

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.