Davood
Davood

Reputation: 5645

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?

Upvotes: 6

Views: 2094

Answers (2)

phil soady
phil soady

Reputation: 11348

Im using DbContext. There are several Overload Constructors eg: ObjectContext also has a similar set of constructor overloads.

System.Data.Entity DbContext example

Context = new BosMasterEntities(nameOrConnectionString: nameOrConnectionString);

You can connect to multiple Dbs at same time.

Upvotes: 1

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364389

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) { }
}

Upvotes: 2

Related Questions