SzilardD
SzilardD

Reputation: 1751

Entity Framework core navigation property between two contexts

There are similar questions with this issue, but not for EF Core. Not a duplicate of Entity Framework Core Using multiple DbContexts . That one is related to not being able to access the database at all from the second context, and the two contexts use different databases. This question is about a single database and the issue is related to migrations


I have two EF core db contexts using the same SQL Server database.

In the first context I have many entities, one of them is User.

In the second one there is a single entity called UserExt which has a navigational property to User

public class UserExt
{
    [Key]
    public long UserID { get; set; }
    public virtual User User { get; set; }

    [Required]
    public string Address { get; set; }
}

The issue is that when creating the migration for UserExt using 'add-migration', all entities from the first context are also included.

Tried providing the context, but same result

add-migration --context SecondContext

With EF 6 it was possible to solve this using ContextKey (https://msdn.microsoft.com/en-us/library/system.data.entity.migrations.dbmigrationsconfiguration.contextkey(v=vs.113).aspx) but has not been ported to EF Core

Is there a way to make this work so that the migrations in the second context would contain only its entities ?

Upvotes: 2

Views: 1960

Answers (1)

SzilardD
SzilardD

Reputation: 1751

Solved using database context inheritance. This way I can have separate migrations.

public class SecondDbContext : FirstDbContext
{
    public virtual DbSet<UserExt> ExtendedUsers { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
       optionsBuilder.UseSqlServer("connectionString", options => 
            options
               .MigrationsAssembly("SecondDbContextAssemblyName")
               .MigrationsHistoryTable("__SecondEFMigrationsHistory") // separate table to store migration history to avoid conflicts
       );
    } 
}

Because SecondDbContext is inherited from FirstDbContext, every entity change made in the base context will be inherited. Which means that when a new migration is added to the second context, it will try to apply the changes again from the first context again. Workaround is to:

  • Add a new migration (for example Add-Migration Inherit_FirstDbContext)
  • Delete everything from the migration's Up and Down methods
  • Apply the empty migration in the database. (Update-Database)

This ensures that the Entity Framework snapshot will contain the changes, without actually having to re-apply them in the database.

Upvotes: 1

Related Questions