Monday, 23 January 2012

DataContext in LINQ


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
  1. Create connection to database.
  2. It submits and retrieves object to database.
  3. Converts objects to SQL queries and vice versa
image
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.
image
It may take
  1. Connection string
  2. IDbConnection etc
Various public methods of DataContext class help us to perform below tasks
  1. Create data base
  2. Delete data base etc
You can create and drop a database like below,
Create database
clip_image002
Delete database
clip_image004
Full source code is as below,
01using System;
02using System.Collections.Generic;
03using System.Linq;
04using System.Text;
05using System.Data.Linq;
06 
07namespace ConsoleApplication1
08{
09    class Program
10    {
11 
12        static void Main(string[] args)
13        {
14 
15            DataContext context = new DataContext(GetConnectionString("Yourservername"));
16            bool dbExist = context.DatabaseExists();
17            if (dbExist == true)
18            {
19 
20                context.DeleteDatabase();
21                Console.WriteLine("Database deleted");
22            }
23            else
24            {
25                context.CreateDatabase();
26                Console.WriteLine("Database created");
27            }
28            Console.ReadKey(true);
29 
30        }
31 
32        static string GetConnectionString(string serverName)
33        {
34 
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;
43 
44        }
45    }
46}
Strongly Typed Data Context
Strongly typed Data context can be created by below steps
  1. Create class to represent strongly type data context
  2. Inherits the class from DataContext class.
clip_image002[5]
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   Smile

No comments :