LINQ to SQL is a component of the .NET Framework version 3.5. Click to learn more about LINQ to SQL
First of all, in your Project or Website, add a new item from the “LINQ to SQL” template. This will create a file with extention “.dbml” and code behind files. Now from Server Explorer, drag and drop the required Tables from the DB. At this point, we will be able to save the Server Connection String to connect to the Database automatically. If its a Web application, it will be saved in web.config and for Windows Project, it will be saved in Settings.settings file.
Now create a new Class with the name “DataContextFactory”. Include the following namespaces;
using System.Configuration;
using System.Data.Linq.Mapping;
using System.Data.Linq;
Now include the following code;
{
private static readonly MappingSource _mappingSource;
static DataContextFactory()
{
_connectionString =
DataContext context = new DataDataContext(_connectionString);
_mappingSource = context.Mapping.MappingSource;
}
public static DataDataContext CreateContext()
{
return new DataDataContext(_connectionString, _mappingSource);
}
}
In the above code, “MyConnectionString” is the value given to the “Name” property of the Connection String used to connect to the server containing the database. It is found in web.config or Settings.settings.
In part two i will include details of how to use the DataContextFactory to connect with DB and Get, Insert, Delete, Update the Database.