How to create a fully customizable / shared LINQ to SQL database connection?

For an ASP.NET C # application, I would like to use LINQ to SQL to query the SQL database for which I defined the connection string in the web.config file. I used the wizard in Visual Studio 2010 to create LINQ classes. However, when checking, the .dbml file explicitly contains the database name and the connection string that I use (on 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 which connection strings and database name my clients will choose ahead of time, and I would like them to only modify the web.config file to configure the connection to the database.

, , ?

.

+3
1

, . , .

- DataContext OnCreated partial method, . , ConnectionString web.config ConnectionString.

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

Source: https://habr.com/ru/post/1791105/


All Articles