6

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?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
motevalizadeh
  • 5,244
  • 14
  • 61
  • 108

2 Answers2

2

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) { }
}
Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
  • error:Code generated using the T4 templates for Database First and Model First development may not work correctly if used in Code First mode. To continue using Database First or Model First ensure that the Entity Framework connection string is specified in the config file of executing application. To use these classes, that were generated from Database First or Model First, with Code First add any additional configuration using attributes or the DbModelBuilder API and then remove the code that throws this exception. – motevalizadeh Sep 30 '12 at 13:39
  • How does your connection string look like? – Ladislav Mrnka Sep 30 '12 at 14:32
  • "data source=|DataDirectory|\\MyDb.sdf;password=xxx;persist security info=True"; – motevalizadeh Sep 30 '12 at 14:38
  • 1
    Are you using EDMX? This is not valid connection string when EDMX mapping is used. You must use connection string in the same format used in app.config. – Ladislav Mrnka Sep 30 '12 at 19:58
1

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.

phil soady
  • 11,043
  • 5
  • 50
  • 95