1

I created a database in Azure setting my own custom name. I then created EF 5 code first entities and added migrations. On application startup I called these two lines:

        Database.DefaultConnectionFactory = new SqlConnectionFactory(connectionString);
        Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyDataContext, MyConfiguration>());

Connection string is taken straight from Azure: Server=tcp:xxx.database.windows.net,1433;Database=dbName;User ID=yyy;Password=zzz;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;

On fist call I expected database dbName to be filled with tables according to POCO schema. But instead a NEW database is generated with the complete namespace name of my context: MyService.Business.Entity.MyContext

Why will the migration not accept the database name specified in the connection string?

Jakob Lithner
  • 4,225
  • 6
  • 38
  • 59
  • 1
    if you don't pass the connection string as shown by Chris below EF will try using a connection string from the config file whose name is the same as the context name. If it is not found it will create its own connection string where the database name will be created based on context name – Pawel Apr 09 '13 at 02:52

2 Answers2

1

My experience is that, in the case where the connection string is being passed in code, rather than obtained from app.config, EF is quirky about how it obtains the connection string.

I had to add a class that inherited from IDBContectFactory

  public class ContextFactory : IDbContextFactory<Context>
  {
    public Context Create()
    {
        var s = (string)AppDomain.CurrentDomain.GetData("ConnectionString");
        var context = new Context(s);

        return context;
    }
}

Also, in order to create a migration, I needed the following in my context class

// uncomment when creating migration - comment out after migration is created
public Context() : base("ConnectionStringName"){}

Where the ConnectionStringName is set up in my app.config.

I am still mystified that I had to do this and have asked about it here

Community
  • 1
  • 1
Kirsten
  • 15,730
  • 41
  • 179
  • 318
1

You can specify the Database name or connection string name in the constructor of your DbContext:

public class MyDataContext : DbContext
{
    public MyDataContext: base("DbNameOrConntectionStringNameHere")
    {
    }
}
Chris Curtis
  • 1,478
  • 1
  • 10
  • 21
  • It is strange that the database needs to be specified twice to get it working, but at least it works. Thanks! – Jakob Lithner Apr 10 '13 at 20:00
  • You don't _have_ to specify it twice. Generally I don't specify a connection string to the connection factory, just one in the standard connectionStrings config section. – Chris Curtis Apr 10 '13 at 20:50