LINQ-To-SQL DataContext and NullReferenceException

2009 June 13
tags: , ,
by r.claypool

LINQ classes generated by the VS designer (or sqlmetal.exe) are marked partial by default.

[System.Data.Linq.Mapping.DatabaseAttribute(Name="MyData")]
public partial class MyDataDataContext : System.Data.Linq.DataContext
{
    // blah ... blah ...
}
public partial class MyDataDataContext
{
    // My additional methods, constructors, etc.
}

As I’ve shown above, this allows you to extend a class without modifying the original code. The additional class definitions just live somewhere else, typically in another file, and the compiler integrates them as needed. That’s great for keeping your code out of the machine generated file, but you still need to be aware of what the machine generated code is doing before you extend it! One thing to check is the default (sqlmetal generated) constructor when you are planning to overload it with your own. In some cases, the default constructor will initialize dependencies, so if you write an overload, make sure it calls the default constructor too:

public partial class MyDataDataContext
{
    public MyDataContext() : this() // We must call the designer generated constructor because it contains initialization code.
    {
        // blah ... blah ...
    }
}

Notice how I used the constructor initialization keyword : this().
From the C# Specification Section 10.10.1

“An instance constructor initializer of the form this(argument-listopt) causes an instance constructor from the class itself to be invoked.”
If your DataContext is throwing a NullReferenceException “Object reference not set to an instance of an object”,  make sure you are calling the default constructor.
Don't forget to call the default constructor!

Don't forget to call the default constructor!

Happy Coding!

No comments yet

Leave a Reply

Note: You can use basic XHTML in your comments. Your email address will never be published.

Subscribe to this comment feed via RSS

This work by Robert Claypool is licensed under a Creative Commons Attribution 3.0 United States.