Code First migrations updating the wrong Db on loc

2019-05-18 09:50发布

问题:

I am using code first migrations to create and update the database for my asp mvc site.

I have a DbContext, which is in another project in the solution.

public class EFDbContext : DbContext
{
    public DbSet<Book> Books { get; set; }
    public DbSet<Author> Authors { get; set; }
    public DbSet<Publisher> Publishers { get; set; }
}

When i enable-migrations and add-migration [name]. It seems to create its own db called

[foo-projectname].Domain.Concrete.EFDbContext

Instead of the attaching to the database i created, called [foo-projectname]. In the webconfig for the site the connection string is referencing by catalog "[foo-projectname]".

If i change the webconfig to the other database , then i get results back from items i have added into the that database. However i want to use the database that i created.

The reason i do not want to stick with this auto created one is because i am not sure on the migration to SqlServer and do not want to get stuck further down the line. I am also getting the error

The model backing the 'EFDbContext' context has changed since...

even when i have not changed anything.

回答1:

X is the project name that contains derived DbContext class.

  • Make sure the Default project on Package Manager Console is X
  • Make sure the active start up project on the solution is X

Another workaround is, provide following parameters when running the migration syntax.

-ProjectName X -StartUpProjectName X

Some Parameters Description:

-ProjectName <String>
    Specifies the project that contains the migration configuration type to be
    used. If omitted, the default project selected in package manager console
    is used.

-StartUpProjectName <String>
    Specifies the configuration file to use for named connection strings. If
    omitted, the specified project's configuration file is used.

-ConfigurationTypeName <String>
    Specifies the migrations configuration to use. If omitted, migrations will
    attempt to locate a single migrations configuration type in the target
    project.

-ConnectionStringName <String>
    Specifies the name of a connection string to use from the application's
    configuration file.

-ConnectionString <String>
    Specifies the the connection string to use. If omitted, the context's
    default connection will be used.