ef core: There is already an object named in the database

asp.net-core database entity-framework entity-framework-core


Hi I am working on an aspnet core app, which using ef core version :

"Microsoft.EntityFrameworkCore.Design": "1.1.0", "Microsoft.EntityFrameworkCore.SqlServer": "1.1.0"

and dotnet standard 1.6.1.

here is my scenaro:

  1. 4 dbcontext with only a database
  2. DBSet or anyother may shows in two or three contexts, for example AContext contains tableA, BContext also contains tableA. but none of them will include all tables as i want to the specific context focus on its purpose.
  3. many foreigne keys between tables

this causes the dup table in database, but to resolve this, i have done below

  1. create a MigrationDBContext to include all DBSet
  2. add migration on this MigrationDBContext

here are what i get

  1. successfully create the database and tables with right schema and name
  2. error when call : serviceScope.ServiceProvider.GetService().Database.Migrate(); error message: There is already an object 'A' named in the database.

unfortunitly, the update-database command in ef core with -v will not show the sql script, Script-Migration shows only the simple create sql statement.

my questions are

  1. how to debug such of this situation?
  2. Checked the migration file, there do have a down and up method, but this error seems like the ef core only call the up method in migration file without calling the down first, and result some dup as the table is still there. so, is there any switch to control the migration behavior?
11/17/2016 5:14:07 PM

Accepted Answer

The simplest way is create the one DbContext that will include all sets of entities and relations between them. After that you can separate storage logic with repositories. The hard way is create context-specific migrations for each context. And if you need to add set of entities, that exists in another context - you will need to create an empty migration for that context. This is a little bit dirty way.

11/18/2016 6:09:59 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow