How to read SQL server schema info in .net? - c#

How can I know in C# the list of Tables in database.
The list of columns each tables has with complete specification like column one is Id and it has data type of int(50), etc

Use the GetSchema method of the SqlConnection class:
DataTable t = _conn.GetSchema("Tables");
For more info read the MSDN article Retrieving Database Schema Information (ADO.NET). Note that this will get you the results without having to write or directly pass/execute any SQL.

Use the information schem views
http://msdn.microsoft.com/en-us/library/ms186778.aspx
Thy are the "standardized way to look at that and contrary to the sys tables quite guaranteed not to change (while the sys.* tables are an implementation detail).

We have previously used SQL Server Management objects with good success. SMO allows you to interact with the SQL Server quite easily thorugh C#. You just need to reference some DLLs and use the object model provided by them. For example, to list the tables you can use the foreach to iterate over the Database.Tables -property.
Codeproject has an article which goes through the basics: http://www.codeproject.com/KB/database/SMODemo.aspx

Related

Data transfer from One database to another

I am looking for an idea or some direction. I have to transfer data from one database to another both are structurally and schema wise same.
Its a complete database with maybe 70 tables and having relationship between tables at different levels. Even though i ' m going to mess up the identity when i move across database but as of now i am ok with it.
Idea which i thought was to load required data from all table into an XML and then create connection to second database and push data from this XML its kind of repeated and not best way at all. So looking for direction.
Can i use entity framework for this somehow??
I cannot use SSIS for this it has to be C# Sorry.
You can create a linked server as stated in the comments to your question. You seemed to indicate that you know how to do this, but in case not, you can do this from SQL Server Management Studio by drilling down to "Server Objects > Linked Servers" beneath your source database on the source database server, then right-click, "New Linked Server", etc.
Then you would use a statement like this, for example, from your C# code:
insert into DestServer.DBName.dbo.TableName
select * from SourceServer.DBName.dbo.TableName
Assuming you are connected to 'SourceServer' and that 'SourceServer' maintains a linked server object pointing to 'DestServer'. Note: you don't actually need to use the fully-qualified name for the table on 'SourceServer', but I've put it there for clarity. I.E. you could also do this:
insert into DestServer.DBName.dbo.TableName
select * from TableName
Don't forget to setup the permissions properly in your linked server object so that your query can write to the table in the destination server. You can do this any number of ways, and often (because I work in a small environment where it's maintained by just me and a couple other folks) I just use the "sa" login:
Yes, can use linked servers in .NET.
You just use the 4 part name.
What you can do in TSQL in SSMS you can do in a .NET SQLcommand.
My experience is that you get better performance connecting to the server you are writing to.

Sql Server class in C# for all request?

I'm looking for a class for Sql Server. I need to make insert, update, delete, select (retrieve many rows and columns) and execute Stored Procedure.
I didn't find a sample of this sort of class and i didn't want to reinvente the wheel.
Somebody can give it to me?
You sound like you may be looking for a ORM (Object Relational Mapper). There are a great number available, some built right it to the .NET framework itself. Look at the various websites and see if you can find one that fits your needs.
There's not a single class that does this, but instead a set of a few classes you need to know:
Sql Server specific:
System.Data.SqlClient.SqlConnection
System.Data.SqlClient.SqlCommand
System.Data.SqlClient.SqlDataReader
System.Data.SqlClient.SqlDataAdapter
System.Data.SqlClient.SqlParameter
Used by all database types
System.Data.DataTable
System.Data.DataSet
System.Data.SqlDbType (enum)
There are others as well, but these are the main ones. Together, these make up the ADO.Net API, and the Sql Server provider for the ADO.Net API.
Additionally, there are a number of Object Relational Mappers that build on top of ADO.Net to try to make this easier. Entity Framework, Linq To Sql, and NHibernate are of a few of the more common options. One common characteristic of ORMs is that they try to free you from even knowing the sql language. If you want to write your own SELECT/INSERT/UPDATE/DELETE queries, which it sounds like you do, you should start at the native ADO.Net level.
To put your data access in one object, you create your own class that makes use of these other types. Don't try to build a new public method that accepts an sql string. Build individual methods for each query you will want to run that include the needed sql as part of the method, and have those methods use these types to change or return data.
You might be interested in this tutorial.
There is builtin functionality (System.Data.SqlClient) to simply access an SQL server.
There is no single class that can do everything you need. Whatever choice you decide you would necessarily need to deal with multiple classes.
Look at it this way – in order to get data from SQL Server you need to typically do following things:
Open connection
Crete SQL query
Execute SQL Query
Accept results
Close connection
Putting all this functionality into a single class would make the class way too complex.
Here is a good reading material for what you need.
Beginners guide to accessing SQL Server through C#

What is best way access different database on different engine but with similar structure

I usually work with MySql, but also with SQL Server, Oracle and Access, the database structure is almost the same. My database stores configuration and recorded data of a SCADA application ("Supervisory Control And Data Acquisition").
Most of the tables are usually the same but sometime my teammates adds fields, tables or changes some fields type.
I'm writing an application that need to load some config parameters from db, then load data, process it and store the new values on db. It also need to add new records.
I have a class that, independently from db type, given the correct connection params, gets a IDbConnection object. With some methods I can specified a SQL query and it give me and IDataReader or a also Dataset.
Now, how should i query data from the db, analyze, recalculate, and finally store them again?
I'm a bit scared of building a detailed object mapping because of the possibility of changed fields. A simple dataset/datatable/datarow should be ok but i'd like to use linq to query in a simpler way the extracted data from the database.
Finally, my db has about 60 tables but in this application I work only with a dozen of them. I have only a few time to build that application, so I need a fast way, also if it's not "very beautiful".
Thanks.
you should try an ORM that configures itself automatically according to schema
i have found this one. I didn't use similar things in c# but it works nicely in other (dynamic) languages.
http://www.codeproject.com/Articles/117666/Kerosene-ORM
Using an ORM would most probably be the fastest. You could use NHibernate which has multiple DB support. NHibernate does have a learning curve, so something like a micro ORM could be easier to use perhaps. Petapoco is a great micro ORM and supports SQL Server, SQL Server CE, MySQL, PostgreSQL and Oracle.
These ORMs would create a mapping file for each DB you use which needs to be updated or recreated when changes are made in the DB.

The DataContext object (LINQ to SQL)

I've read about ways to synch my SQL database with my C# code, and it looks like the DataContext object is the way I'm going to go.
After having read up on what it can do, I find myself still slightly confused on its exact capabilities. For instance, once set up, does the DataContext linked to my SQL database contain a property for each table? And does that table object then contain a list of items, each of which holds the data for each table entry?
In addition, I'm not sure how to instruct it to generate me the code (since I've read that it does generate the necessary objects). How is this achieved?
The Gu (Scott Guthrie) has an excellent article series about Linq to Sql that introduces this concept: http://weblogs.asp.net/scottgu/archive/2007/05/19/using-linq-to-sql-part-1.aspx
Good luck!
"does the DataContext linked to my SQL database contain a property for each table"
YES you will be able to accesss all the table and properties,
that you have used in your datacontext (.dbml) file
Anyway, please read this article about LINQ TO SQL. Also there are some good video tutorial about ASP.NET 3.5 LINQ TO SQL
Hope this help
What have you tried so far?
There are two ways to generate the code:
In Visual Studio, on your project, add a new item of type "LINQ to SQL classes". Then drag-and-drop the tables you want in your project onto the drawing space. This is the most simple, but there is no support for refreshing the model if you change the database.
Use the commandline tool SqlMetal.exe to generate the classes.

Retrieve Database Schema

I want to know, how can I retrieve Sql-Database schema informations such as Tables, Columns and Their relation between Tables and etc. I know it's possible if I execute different particular queries on Master Database and the targeted Database. But Is there any efficient way to retrieve schema of database ?
Thanks in advance.
Take a look at this project on codeplex:
http://dbschemareader.codeplex.com/releases/view/71696
You can obtain the database metadata via GetSchema method of Connection class.
try to follow those articles.
http://support.microsoft.com/kb/309681/en
http://support.microsoft.com/kb/310107/en
Regards
Use the GetSchema method of the SqlConnection class:
DataTable t = _conn.GetSchema("Tables");
For more info read the MSDN article Retrieving Database Schema Information (ADO.NET)..
GetSchema and Schema Collections
The Connection classes in each of the .NET Framework managed providers implement a GetSchema method which is used to retrieve schema information about the database that is currently connected, and the schema information returned from the GetSchema method comes in the form of a DataTable. The GetSchema method is an overloaded method that provides optional parameters for specifying the schema collection to return, and restricting the amount of information returned.
http://msdn.microsoft.com/en-us/library/ms254934(v=vs.110).aspx

Categories