SQL Server Finding all database names using Linq
This is a quick and easy way of using Linq Lambda expression to interrogate the SQL server sys.database.

Data class table
First thing is to create the database table class. This example will contain only a name property, but you can add how many or all the sys.database fields.

[Table(Name = "sys.databases")]
public class DatabaseTable
[Column(Name = "name")]
public string Name { get; set; }

Connecting to the server
For this all you need to do is create a DataContext (I'm using DataContext, but it does not stop you using something else).
You will need to use a user, which has permissions to query the sys databases

private static string connectionString = "data source={0};initial catalog={1};persist security info=True;User ID={2};Password={3};";
public static DataContext Load()
string connection = String.Formate(connectionString,SERVERNAME,DATABASENAME,USERNAME,PASSWORD)
return new DataContext(connection);

Run the query
Now all you need to do is run the below code and you will get the database's on the server

public static List<string> GetServerDatabases()
using (System.Data.Linq.DataContext sysContenxt = Models.DataManager.Helpers.ContextHelper.Load())

var table = sysContenxt.GetTable();
var results = table.Select(s=>s.Name).ToList();

return results;



Now how simple was that?

Latest blogs

Buy me a coffeeBuy me a coffee
Created: 07/09/2017 Total Comment: 0


(Not Displayed)
Human validation
Enter 2187 number, before submitting to confirm your human
[Home] [All Blogs] [Contact] [Me]
Buy me a coffeeBuy me a coffee