Connect and Select Data using C# LINQ to SQL DataContext

Updated on 06 Apr 2012,
Published on 23 Nov 2010

The DataContext created by LINQ to SQL O/R mapping tool consists of its default constructors which initializes the connection to database when an object of DataContext class is created. In the previous tutorial: Creating LINQ to SQL entity classes we created the entity classes for Categories and Products table of Northwind SQL database by dragging and dropping them on the designer surface of O/R designer. It will create the following constructors for NorthwindDataContext class generated by the tool:

public NorthwindDataContext() : 
  base(global::System.Configuration.ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString, mappingSource)
{
 OnCreated();
}
  
public NorthwindDataContext(string connection) : 
  base(connection, mappingSource)
{
 OnCreated();
}
  
public NorthwindDataContext(System.Data.IDbConnection connection) : 
  base(connection, mappingSource)
{
 OnCreated();
}
  
public NorthwindDataContext(string connection, System.Data.Linq.Mapping.MappingSource mappingSource) : 
  base(connection, mappingSource)
{
 OnCreated();
}
  
public NorthwindDataContext(System.Data.IDbConnection connection, System.Data.Linq.Mapping.MappingSource mappingSource) : 
  base(connection, mappingSource)
{
 OnCreated();
}

The first DataContext constructor initializes the database connection using the connection string created inside the web.config file globally. Following C# code example illustrates the use of NorthwindDataContext class object to connect to database and fetch the records from a table:

// create datacontext object
NorthwindDataContext db = new NorthwindDataContext();
            
// LINQ to SQL to fetch the Categories
// from Northwind database
var query = from category in db.Categories
            select category;

foreach (var category in query)
{
    Response.Output.Write("{0}<br />", category.CategoryName);
}

// Output:
// Beverages
// Condiments
// Confections
// Dairy Products
// Grains/Cereals
// Meat/Poultry
// Produce
// Seafood

The above C# sample code shows how to create the NorthwindDataContext class object to connect to the Northwind database and fetch all the categories.

Continue to next tutorial: Insert, Update and Delete using C# LINQ to SQL DataContext to learn how to submit the changes to the database.

0 Responses to "Connect and Select Data using C# LINQ to SQL DataContext"
Leave a Comment
* required
* required
* will not be published
* optional
* hint: http://www.example.com
  • Subscribe via Email