开发者

How do I make a LINQ to SQL database connection fully configurable / generic?

开发者 https://www.devze.com 2023-02-09 09:18 出处:网络
For an ASP.NET C# app, I\'d like to use LINQ to SQL to query a SQL database, for which I have defined a connection string in the web.config file. I used the wizard in Visual Studio 2010 to create the

For an ASP.NET C# app, I'd like to use LINQ to SQL to query a SQL database, for which I have defined a connection string in the web.config file. I used the wizard in Visual Studio 2010 to create the LINQ classes. However, upon inspection, the .dbml file explicitly contains the database name and connection string I'm u开发者_Go百科sing (in my dev system), and the .designer.cs file also explicitly names the database.

For example, in my .dbml file:

   <?xml version="1.0" encoding="utf-8"?>
<Database Name="MyDatabaseName" Class="MyLinqDataContext"
xmlns="http://schemas.microsoft.com/linqtosql/dbml/2007">
<Connection Mode="WebSettings" ConnectionString="XXX"
SettingsObjectName="System.Configuration.ConfigurationManager.ConnectionStrings"
SettingsPropertyName="MyConnectionString" Provider="System.Data.SqlClient" />

and in my .designer.cs file:

[global::System.Data.Linq.Mapping.DatabaseAttribute(Name="MyDatabaseName")]

Although the table structures will be static, I don't know what the connection string and database name my customers will choose ahead of time, and I'd like them to only have to change the web.config file in order to configure the database connection.

How do I set this up so that I don't have to compile or release static dev settings into the release build of my product, allowing my customers to configure everything in one place?

Thanks.


Check this explanation

You can Initialize your data context with the connection string fetched from your config file. That overrides default connection string used in your designer file.

Another way is creating your own partial DataContext class and adding the OnCreated partial method which gets called in the default constructor. Here is a simply implementation where I am reading the ConnectionString from web.config ConnectionString section.

  Partial class MyDataContext
    {
        partial void OnCreated()
        {
            this.Connection.ConnectionString = 
             ConfigurationManager.ConnectionStrings["myconnection"].ConnectionString;
        }
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消