LINQ2SQL – Object reference not set to an instance of an object

October 18, 2012

Object reference not set to an instance of an object.

Stack Trace:    at YourDataContext..ctor() in

This is caused by dragging a stored procedure/table onto the surface designer from a different connection in server manager to the one you used previously, which means the designer has used the new connection string (And created a new one in web.config), and the developer has subsequently deleted the connection string from web.config.

Solution: open the designer file for your datacontext (automatically generated file –  YourDataContext.designer.cs) – Around line 42 you’ll find a constructor (which takes 0 params), within this you’ll see a reference to the connection string in web.config – This will not match your actual connection string, change it to match and all should be good!

To avoid this in future, ensure that your connection in server manager is using the same server/credentials each time you add an object to the surface designer – e.g. Don’t drag sprocs/tables from a mixture of your live/development/staging/etc databases, stick to one database (Probably your development database) and add a connection string for the live one when you publish – Or better still, consider using Web.Config XDT (XML Data Transformations) to manage your connection strings between live/dev/staging etc which makes life much easier!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: