Sunday, April 25, 2010

How to make “LINQ to SQL” in a Class library refer to web.config connectionstring?

Creating LINQ to SQL classes in a DAL class library and reference it in a test project then publish the application on testing server, update the connection string with the testing server setting.

i try to open the test page which consume my “LINQ to SQL” classes, i got the error page say that the SQL Server doesn’t exist!! Luckily I have a login page using membership provider and it is working properly then the Server exists and the connection string is correct (Saved my day) so my problem is in the LINQ to SQL classes.

I found an easy way to fix this by passing the connection string in the LINQ context like this          

using(TestProjectDataContext context = new TestProjectDataContext(ConfigurationManager.ConnectionStrings[0].ConnectionString))
{
    // Implementation here
}

Since this is a test project it was easy to change, I didn’t know why it work fine locally without passing the connection string and fail on the hosting server!!

Later i discovered that this can be fixed by changing the web.config connectionstring name to a fully qualified one like this

<connectionStrings>
        <!-- 
            This one will not work for LINQ to SQL
            <add name="TestProjectConnectionString"
            connectionString="Data Source=.;Initial Catalog=IslamDB;Integrated Security=True"
            providerName="System.Data.SqlClient" /> 
        -->
            <add name="TestProject.DAL.Properties.Settings.TestProjectConnectionString"
            connectionString="Data Source=.;Initial Catalog=IslamDB;Integrated Security=True"
            providerName="System.Data.SqlClient" />
    </connectionStrings>
 

I like it that way

No comments: