How to programmatically set the connection string when the DBML is in a library project

In my previous post I wrote about using Linq-to-Sql and the Repository pattern. Typically, this means the dbml file is located in a repository project, which is a separate library project. In other words, the dbml files does not have direct access to the web.config connection strings of your web (presentation) project. The dbml designer is configured using the app.config settings, instead.

On the other hand, the web.config debug/release build mechanism is too handy to ignore when it comes to connection strings. So, can the dbml be programmatically configured to use the appropriate web.config's connection string and if yes, how?

The answer lies in the connection string passed as a parameter to the DataContext constructor thus overriding the dbml designer's property. This becomes even easier when using the Repository pattern since there is a single point of construction: the Repository class constructor. The following code snipet demonstrates the solution discussed. Please note, that the presented abstract Repository class is to be as base to all other type-specific repository classes.

public abstract class Repository<T> where T : class
{

protected VioDataContext dataContext;

public Repository()
{

dataContext = new DataContext(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);

}

}

Share


Έχουν δημοσιευτεί Σάββατο, 18 Μαΐου 2013 8:47 μμ από το μέλος dpant
Καταχώρηση στις κατηγορίες: , , , , ,

Σχόλια:

Χωρίς Σχόλια