DataContext in LINQ



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.

    Untitled-8.gif

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.

Untitled-9.gif
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
Untitled-11.gif
Delete database
Untitled-12.gif
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)
            {
                context.DeleteDatabase();
                Console.WriteLine("Database deleted");
            }
            else
            {
                context.CreateDatabase();
                Console.WriteLine("Database created");
            }
            Console.ReadKey(true); 
        } 
        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";
            Console.WriteLine(builder.ConnectionString);
            Console.ReadKey(true);
            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.

    Untitled-13.gif

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.

Up Next
    Ebook Download
    View all
    Learn
    View all