Reader Level:

DataContext in LINQ

By Dhananjay Kumar on Jun 24, 2011
To communicate with a Database a connection must be made. In LINQ this connection is created by a DataContext.

To communicate with a Database a connection must be made. In LINQ this connection is created by a DataContext.

Essentially a DataContext class performs the following three tasks:

  1. Create connection to database.
  2. It submits and retrieves object to database.
  3. Converts objects to SQL queries and vice versa.


You can say, it acts exactly the same as the SqlConnection class but performs some extra tasks as well, like conversion of objects to SQL queries.

A DataContext class has four types of overloaded constructor.

It may take:
  1. Connection string
  2. IDbConnection etc

Various public methods of the DataContext class help us to perform the following tasks:
  1. Create data base
  2. Delete data base etc

You can create and drop a database like below:

Create database
Delete database
The full source code is as below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq; 
namespace ConsoleApplication1
    class Program
        static void Main(string[] args)
            DataContext context = new DataContext(GetConnectionString("Yourservername"));
            bool dbExist = context.DatabaseExists();
            if (dbExist == true)
                Console.WriteLine("Database deleted");
                Console.WriteLine("Database created");
        static string GetConnectionString(string serverName)
            System.Data.SqlClient.SqlConnectionStringBuilder builder =
                           new System.Data.SqlClient.SqlConnectionStringBuilder();
            builder["Data Source"] = serverName;
            builder["integrated Security"] = true;
            builder["Initial Catalog"] = "Sample2";
            return builder.ConnectionString; 

Strongly Typed Data Context

A Strongly typed data context can be created by the following steps:
  1. Create a class to represent a strongly type data context
  2. Inherit the class from the DataContext class.


The advantage of using a strongly typed data context is that each table is available in table collections. So you do not need to fetch tables using a GetTable method.

I hope this article was useful. Thanks for reading.

Dhananjay  Kumar
Dhananjay Kumar

Dhananjay kumar is 6 times Microsoft MVP, 7 times C# Corner MVP. He works as consultant for Infragistics in India. He is known for mentoring teams on various technologies.

Personal Blog: