Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
777 views
in Technique[技术] by (71.8m points)

linq - Point connectionstring in dbml to app.config

Can I just point the connection string in Dbml.designer.cs to the connectionstring in the app.conf? I wrote the code below which it successfully point to the app.config.

public leDataContext() : 
    base(ConfigurationManager.ConnectionStrings["leConnString"].ToString(), mappingSource)
    {
        OnCreated();
    }

However whenever i modify or add a table into the dbml, it will start to auto replace that code into this

 public leDataContext() : 
            base("Data Source=.\SQLEXPRESS;AttachDbFilename="D:\My Projects\App_Data\le.mdf";Integrated Security=True;Connect Timeout=30;User Instance=True", mappingSource)
    {
        OnCreated();
    }

I have expanded the "Connection" option. Set "Application Settings" to False

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is more like an extension to @Alex's answer.

Step 1 : Set the connection property of your .dbml file to “none”.

enter image description here

Step 2 : Create a new separate partial class with the same name as that of the existing partial class for the .dbml file. And set the connectionString property by using the parameterless constructor.

public partial class DataClassesDataContext
{
  public DataClassesDataContext() : base(ConfigurationManager.ConnectionStrings["Dev-connString"].ConnectionString)
  {
    OnCreated();
  }
}

Step 3 : Almost Done ! Lastly you need to define your connectionString in your app.config file, as shown below.

<connectionStrings>

  <add
  name="Dev-connString"
  connectionString="Data Source=yasser-home;Initial Catalog=pp;Persist Security Info=True;User ID=sa;Password=gogole"
  providerName="System.Data.SqlClient" />

</connectionStrings>

You can now easily change the connectionString from the app.config file without having to re-compile your code, which would be the case otherwise.

Why did I create a seperate partial class ? Can’t I edit the existing Dbml.designer.cs file ?

Don’t modify Dbml.designer.cs file manually, because it will be rewritten when you add/edit/delete a table, stored proc etc.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...