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?

3
  • Isn't there a constructor that takes a DbConnection as a parameter? Commented Sep 30, 2012 at 12:17
  • yes there is not a constructors to change connection string Commented Sep 30, 2012 at 12:26
  • 1
    can't you just leave in a dummy connection string in the app.config file? Commented Sep 30, 2012 at 12:46

2 Answers 2

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) { }
}
Sign up to request clarification or add additional context in comments.

4 Comments

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.
How does your connection string look like?
"data source=|DataDirectory|\\MyDb.sdf;password=xxx;persist security info=True";
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.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.