This is my first post in a what will become a series of posts on LINQ to SQL. As the title of my blog suggests, I'm going to be "thinking out loud" as I write these and I'm hoping for feedback from others on the pro's and con's of the approaches I'm suggesting. That said, the point of this series of posts will be to define a loose set of best practices around developing with LINQ to SQL in an ASP.Net web environment. The first couple posts will be pretty simplistic but I wanted to get these in place first so I can refer to the concepts later without having to go into detail.
On with the topic at hand...
When starting a new project with LINQ to SQL, it's a good idea to wrap the DataContext with your own class that inherits from the DataContext generated by the designer (or SQLMetal).
Before we do that though, let's take a small step back and talk about namespaces. In the designer, if you click on design surface background, you'll select the DataContext. In the properties window there will be two entries related to namespaces. One is the Context Namespace and the other is the Entity Namespace. Typically you'd put both the generated DataContext and the entity classes within the same namespace, but since we're going to be creating our own DataContext that inherits from the one that is generated for us, I'd suggest that we set these up with different namespaces.
I like to have my data layer to have its own namespace and as such I tend to go with a DB.such_and_such namespace where such_and_such is the name of our database or other logical context name. I'll be using the northwind database for this series of posts, so the logical namespace name is DB.NW. This is what we should put in the Entity Namespace property, but for the Context Namespace, we should set the value to DB.NW.Base to leave room for our custom version in the DB.NW namespace. With our DataContext's name set as simply DataContext as well, we'll get the following generated for us by the designer...
namespace DB.NW.Base
{
...
public partial class DataContext : System.Data.Linq.DataContext
{
...
}
}
namespace DB.NW
{
...
[Table...]
public partial class table_name... etc.
}
Next we need to create a new class file in app_code. In this case I'll keep the name the same as the namespace it contains and go with DB.NW.cs.
using System;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Linq;
using System.Runtime.Serialization;
using System.Reflection;
namespace DB.NW
{
public class DataContext : DB.NW.Base.DataContext
{
}
}
Now, it may seem silly at this point to go through all this but doing this now, even with no custom or overridden methods, will save us from having to change our code later that when we need to override methods such as SubmitChanges()..