Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use dynamic connection string for SQL Server CE?

I used SQL Server CE 4.0 in my windows app and use Entity Framework to create a model of it.

It works fine but my problems is that it doesn't have a constructor to change the connection string, and by default it reads the connection string from the app.config file.

 using (var Context = new MyEntitiesModel(//has no constructor))
 {
        ...
 }

I create a dynamic connection string and

  using (var Context = new MyEntitiesModel())
   {
         Context.Database.Connection.ConnectionString = entityConnection.ConnectionString;
   }

It works fine by this way but if I remove another connection string in app.config file it gave me this.

error = invalid metasource ....

because the default constructor uses it

How can I handle it?

like image 958
motevalizadeh Avatar asked Sep 30 '12 10:09

motevalizadeh


People also ask

How can I set an SQL Server connection string?

You can either use the new operator to make that directly. For example: SqlConnection conn = new SqlConnection( new SqlConnectionStringBuilder () { DataSource = "ServerName", InitialCatalog = "DatabaseName", UserID = "UserName", Password = "UserPassword" }. ConnectionString );

What is dynamic connection string?

A dynamic connection string is a connection string that is resolved at the time the database connection is opened, rather than at the time the connection string is defined. This is useful in SaaS applications where client data is stored in different systems of record located on different servers.

Which syntax should be used for a SQL Server Compact connection string?

The file path and name of the SQL Server Compact database. To indicate a relative path to the database from the application directory, use the Data Source = |DataDirectory| (enclosed in pipe symbols) substitution string.

What is ADO connection string SQL Server?

The ADO Connection Object is used to create an open connection to a data source. Through this connection, you can access and manipulate a database. If you want to access a database multiple times, you should establish a connection using the Connection object.


1 Answers

Create your own constructor. MyEntitiesModel is partial class you can add your own partial part of the class and add constructor accepting a connection string.

public partial class MyEntitiesModel {
    public MyEntitiesModel(string connectionString) : base(connectionString) { }
}
like image 67
Ladislav Mrnka Avatar answered Oct 13 '22 11:10

Ladislav Mrnka