linq-to-sqlconnectiondatacontext

LINQ to SQL DataContext and Connection Problems


I am using LINQ to SQL for my website to access two databases. The first database is the website (which i'll call WEBSITE) data, the second is a history of transactions (which i'll call WEBSITE_HISOTRY). When I added a table from the WEBSITE_HISOTRY to my datacontext not so long ago i recieved some sort of alert that I clicked OK on (probably not the best idea). I do recall it was something about Visual Studio complaining that the connection for the database differed from my config or something along those lines. Everything worked fine until I published to my server. I kept getting a database not found error and when I logged the connection strings I found this.

WEBSITE_HISTORY

Data Source=MYCOMPUTER\SQLEXPRESS;Initial Catalog=WebSiteHistory;Integrated Security=TRUE

WEBSITE

Data Source=my.dyndns.net; Network Library=DBMSSOCN; Initial Catalog=Website; User ID=WebsiteUser;Password=*******;

I also found that the constructor for the WEBSITE_HISTORY datacontext required a connection string (unlike the WEBSITE which has a parameterless constructor). I altered the constructor but everytime a I add a table to the datacontext, it changes back. I had read in another question about setting the DataContext connection properties to Application = true. I have tried this but I cannot set the "Settings Property Name" to the correct connection.

Im not sure what I did do incite this behavior. Any help would be greatly appreciated.


Solution

  • The data context should have multiple overloaded constructors available to you; one of them asks for a connection string. I would recommend using this one all the time; the reason is this allows you to change to point to a new database that has the same structure, and it will work that way. I tend to create a static class to create my data context classes to make this easier:

    public static class ContextCreator
    {
       public static CustomDataContext Create()
       {
         return new CustomDataContext(ConfigurationManager.ConnectionStrings["CName"].ConnectionString);
       }
    }