I am using Linq2Sql in VS 2010 (C# .Net 4.0) to handle my database access. This all works great.
But because my DataContext is in a separate layer to my web application (the data access layer) I have configured it to use the connection string in the calling web applications web.config file.
The end result requires one change to be made to the Linq2Sql designer file (DB.designer.cs) and that is to override the first constructor argument (which by default in a string for the DB connection string) and replace it with a call like follows:
System.Configuration.ConfigurationManager.ConnectionStrings["CS"].ConnectionString
The problem I currently seem to be having is that when I update the designer via the GUI designer (the drag and drop part) it resets this code change back to a hard coded connection string.
Can somebody please tell me if I can change a setting to prevent this? Or do I do something with partial classes? or maybe another way entirely?
This is where partial methods come in handy! Thankfully, the LINQ2SQL DataContext is loaded with several very useful ones.
Say your
DataContextis namedAutosDataContextas in my example. Create a new class alongside your DBML and call itAutosDataContext. Then fill it in as follows:The partial
OnCreatedmethod gets called right after the DataContext is instantiated, and makes the perfect place for you to add your custom connection string logic without the DBML designer walking on it on update.