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.
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
Run the query
Now all you need to do is run the below code and you will get the database's on the server
Now how simple was that?
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; }
}
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);
}
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
Created: 07/09/2017 Total Comment: 0