DataContext in LINQ
To make a communication with Database a connection must be made. In LINQ this connection is created by
DataContext.
Essentially Data Context class performs below two tasks
- Create connection to database.
- It submits and retrieves object to database.
- Converts objects to SQL queries and vice versa
You can say, it acts as exactly the same as
SqlConnection class and perform some extra tasks as well like conversion of object to SQL query.
DataContext class is having four types of overloaded constructor.
It may take
- Connection string
- IDbConnection etc
Various public methods of DataContext class help us to perform below tasks
- Create data base
- Delete data base etc
You can create and drop a database like below,
Create database
Delete database
Full source code is as below,
02 | using System.Collections.Generic; |
05 | using System.Data.Linq; |
07 | namespace ConsoleApplication1 |
12 | static void Main( string [] args) |
15 | DataContext context = new DataContext(GetConnectionString( "Yourservername" )); |
16 | bool dbExist = context.DatabaseExists(); |
20 | context.DeleteDatabase(); |
21 | Console.WriteLine( "Database deleted" ); |
25 | context.CreateDatabase(); |
26 | Console.WriteLine( "Database created" ); |
28 | Console.ReadKey( true ); |
32 | static string GetConnectionString( string serverName) |
35 | System.Data.SqlClient.SqlConnectionStringBuilder builder = |
36 | new System.Data.SqlClient.SqlConnectionStringBuilder(); |
37 | builder[ "Data Source" ] = serverName; |
38 | builder[ "integrated Security" ] = true ; |
39 | builder[ "Initial Catalog" ] = "Sample2" ; |
40 | Console.WriteLine(builder.ConnectionString); |
41 | Console.ReadKey( true ); |
42 | return builder.ConnectionString; |
Strongly Typed Data Context
Strongly typed Data context can be created by below steps
- Create class to represent strongly type data context
- Inherits the class from DataContext class.
Advantage of using strongly typed data context is that each table is
available in Table collections. So you do not need to fetch tables using
GetTable method.
I hope this post was useful. Thanks for reading
Posted by
Dhananjay Kumar
No comments :
Post a Comment