in

Blog By Bob

Blog by Bob

My New Favorite .Net Method, GetSchema()

Someone might remember the other day, when I discovered SqlConnectionStringBuilder and fell in love. Well, move over, its a new day! I am piddling around with writing a mini ORM (who isn't now adays) and stumbled across my new love!
As of .NET 2.0, there is a new method hanging off your connection called GetSchema. Say you are writing an ORM and want to get a list of the catalogs in your database:

SqlConnectionStringBuilder connectionStringBuilder = new SqlConnectionStringBuilder();
connectionStringBuilder.DataSource = myServerName;
connectionStringBuilder.IntegratedSecurity = false;
connectionStringBuilder.UserID = userName;
connectionStringBuilder.Password = password;

SqlConnection connection = new SqlConnection(connectionStringBuilder.ConnectionString);
connection.Open();
myBindingDataControl.Enabled =
true;
myBindingDataControl.DataSource = connection.GetSchema(
"databases");
myBindingDataControl.DisplayMember =
"database_name";
connection.Close();

Then once your unsuspecting user has chosen the catalog they want to use, you can quickly grab a list of the tables in the catalog:

SqlConnectionStringBuilder connectionStringBuilder = new SqlConnectionStringBuilder();
connectionStringBuilder.DataSource = myServerName;
connectionStringBuilder.IntegratedSecurity = false;
connectionStringBuilder.UserID = userName;
connectionStringBuilder.Password = password;
connectionStringBuilder.InitialCatalog = cbDatabases.GetItemText(usersCatalogName);

SqlConnection connection = new SqlConnection(connectionStringBuilder.ConnectionString);
connection.Open();
myBindableDataGrid.DataSource = connection.GetSchema(
"tables", new string[4] { usersCatalogName, null, null, null });
connection.Close();

But wait you say! That list has more than tables in it! You would be right. GetSchema also sees views as tables, but I think that is a great thing, since my ORM wants to see Views as well, and you can always get rid of them from your data source if you don't like them. You can also use restrictions to limit by owner and you can grab the columns out of a table in the same way. Here is a nice link that I found when I originally stumbled across GetSchema.

And best of all, GetSchema returns a DataTable natively so you can quickly bing to it, even in Windows Forms, where the DataReader is the evil and won't bind.

Published Dec 28 2006, 10:42 AM by Bob

Comments

 

Elini said:

can I put the connection string in a class, so I don't have to put it in every form?

how use it in form?

June 29, 2008 6:17 AM

Leave a Comment

(required)  
(optional)
(required)  
Add
Copyright © :: BlogByBob.com
Powered by Community Server (Non-Commercial Edition), by Telligent Systems