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.