3

The way that it auto-generates the classes, it doesn't take a connection string as a parameter - although the generates code passes one to the base class. I can edited the template myself, but isn't there a better way, as I may regenerate the model (maybe even delete & re-create) and I don't want it to affect the template.

//------------------------------------------------------------------------------
// <auto-generated>
//    This code was generated from a template.
//
//    Manual changes to this file may cause unexpected behavior in your application.
//    Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

public partial class MyEntities : DbContext
{
    public MyEntities()
        : base("<Connection string>")
    {
    }
...

I am using a DB first approach. It all works fine but now I've created an exact copy of the database and I need to be able to switch between the two.

NibblyPig
  • 51,118
  • 72
  • 200
  • 356

1 Answers1

5

You should be able to define a partial class that sits beside your generated class (in a separate file). This partial class can have the second constructor:

public partial class MyEntities : DbContext
{
    public MyEntities(string connectionstring)
        : base(connectionstring)
    {
    }
}
qujck
  • 14,388
  • 4
  • 45
  • 74
  • Thanks. I've done this, and I get an `UnintentionalCodeFirstException`. Any ideas? Do I just comment it out? – NibblyPig Sep 05 '13 at 10:42
  • The error message implies you can comment it out. Some good info here http://stackoverflow.com/questions/5940616/model-first-with-dbcontext-fails-to-initialize-new-database – qujck Sep 05 '13 at 10:48
  • Commented it out and was careful to include all of the entity information in the connection string, and it worked great. Thanks. – NibblyPig Sep 05 '13 at 12:52
  • @qujck, Is this the default and standard way of doing this? It wasn't like this EF4 which is where I have upgraded from. – IbrarMumtaz Jan 04 '14 at 18:00
  • @IbrarMumtaz As I understand it yes - but I'm not an authority on the topic ;-) – qujck Jan 04 '14 at 21:24