alinaish
alinaish

Reputation: 486

EF5 create database in .\sqlexpress instead localdb?

I use EF5(code first) & VS2012 in my project.

I try to create tables in LocalDb with migrations.

  1. Enable-Migrations
  2. Add-Migration m1
  3. Ubdate-Database

Every time I find my tables not in LocalDb but in sqlexpress, though i create ConnectionString like this:

    <add name="StihlDbContext" connectionString="Server=(localdb)\v11.0;Initial    Catalog=StihlDb;Integrated Security=True" providerName="System.Data.SqlClient" />                               

I don't understand why EF create database in .\SQLEXPRESS but not in LocalDb

Upvotes: 1

Views: 791

Answers (2)

Luci&#235;n Martijn
Luci&#235;n Martijn

Reputation: 1

I encountered the exact same problem. If you had per chance installed EntityFramework in a class library, then you need to set the class library as Startup Project. Otherwise your the connection string in your app.config located in the assembly will not be found and your DbContext instance constructor will have no parameters.

This means that when you run the update-database command in Package Manager Console the database will be created or updated in the default database server, in your case .\SQLExpress

Upvotes: 0

Wiktor Zychla
Wiktor Zychla

Reputation: 48230

I suspect you hit a small issue of the default migrator - instead of migrating the actual database, it creates a new instance of the context using the parameterless constructor. If, by chance, you have the context class in another assembly and there is no local configuration, a default conneciton string will be used.

A workaround: create a local app.config file in the project that the context is defined in. Copy the same connection string so that when the new instance of the context is created, the connection string is used. This will probably work.

Remember that you don't have to migrate from within the Visual Studio. Instead, if you just run your application that creates the context and you set the migrator

Database.SetInitializer( new MigrateDatabaseToLatestVersion<StihlDbContext, Configuration>() );

the database will be automatically migrated upon first use. This is much more convenient than manual updating.

Upvotes: 3

Related Questions