Classes:

public class Document { public int Id { get; set; } public string Title { get; set; } public int UserId { get; set; } /// <summary> /// пользователь который создал документ /// </summary> public User User { get; set; } } public class User { public int Id { get; set; } public string UserName { get; set; } } 

Two DbContext

 public class UserContext : DbContext { public UserContext() : base ("name=ConnectionStringName") { } static UserContext() { Database.SetInitializer<UserContext>(null); } public DbSet<User> Users { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.HasDefaultSchema("User"); base.OnModelCreating(modelBuilder); } } class DocumentContext : DbContext { public DocumentContext() : base("name=ConnectionStringName") { } static DocumentContext() { Database.SetInitializer<DocumentContext>(null); } public DbSet<Document> Documents { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.HasDefaultSchema("Document"); modelBuilder.Entity<User>().ToTable("Users", "User"); base.OnModelCreating(modelBuilder); } } 

UserContext - stores user data (User, Roles, ExternalLogins ...).

DocumentContext -

I create migration for UserContext. The database creates a schema with the necessary tables.

I create a migration for DocumentContext, in the Up EF method I try to create a table that already exists, which is why I get an error:

There is already an object named 'Users' in the database.

 public partial class InitialDocument : DbMigration { public override void Up() { CreateTable( "Document.Documents", c => new { Id = c.Int(nullable: false, identity: true), Title = c.String(), UserId = c.Int(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("User.Users", t => t.UserId, cascadeDelete: true) .Index(t => t.UserId); //EF пытается создать таблицу в схеме User, //Но она уже создана другой миграцией (UserMigrations) //поэтому выходит ошибка - There is already an object named 'Users' in the database. //Как объяснить EF чтобы чтобы он не создавал эту таблицу? CreateTable( "User.Users", c => new { Id = c.Int(nullable: false, identity: true), UserName = c.String(), }) .PrimaryKey(t => t.Id); } //скрыто } 

Question - How to explain EF so that it does not create a user table?

Update

As a temporary solution, I delete the piece of code that creates the migration.

  • Look here . They advise migrations to be done according to one global context, where the entire scheme is defined. And do not touch subcontexts - Vladislav Khapin

1 answer 1

Making migrations in different (several) contexts is not very convenient, and not very good. As far as I know, except for fixing these problems with my hands, that is, removing code that you do not need from the Up and Down methods will not work.

EntityFramework is smart enough, but to solve this problem by hanging a couple of attributes or via OnModelCreating will not work (using modelBuilder.Ignore<Entity>() ), although EntityFramework do this for a short time, just for one database.

Even if you start to get something done in the likeness of what you want - you will encounter a problem that will lead to failure. If you remove references to other classes from properties in classes, it will not pull up other tables, but then it will not create foreign keys.

If you use modelBuilder.HasDefaultSchema("schema") and then when adding a migration, specify the full name of your configuration class (obtained from DbMigrationsConfiguration ) as a parameter in add-migration , thus:

 add-migration NAME_OF_MIGRATION -ConfigurationTypeName FULLY_QUALIFIED_NAME_OF_CONFIGURATION_CLASS 

Too it will not suit you and is unlikely to help.

I see the solution to this collision as follows: create a generalized context and perform migrations for one context. So you will not lose the changes and there will be less conflicts. Link from comment - Entity Framework: One Database, Multiple DbContexts. Is this a bad idea? - a very good example.

If your project is not too large and the separation of models is minimal, then this approach will be simple. But if you have many models, several contexts, common classes and inheritance, you will have to tense up a bit. EntityFramework loves inheritance very much .