EF Core has two DbContexts. How do I specify the tables?

Viewed 727

I have two DbContexts in the database and want to make one of them only reference the one table (class):

dotnet ef migrations add Mall20200325 --context ApplicationDbContext

And in the ApplicationDbContext there is only one DbSet:

public DbSet<Models.User> Users { get; set; }

But it will still migrate other tables.

How to do I accomplish this?

3 Answers

your problem its than you are using two -- instead one

dotnet ef migrations add Mall20200325 -context ApplicationDbContext

I found the following solution from here. Assume you have AccountDbContext and ApplicationDbContext contexts. Assume in the AccountDbContext the entity Account has been defined and we want to exclude accounts table from migration, while we have a reference to it in the User entity. Therefore:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    // Ignored table `accounts` from other DbContext in the migration

    modelBuilder.Entity<Account>(entity => {
        entity.ToView("accounts");
        // If the `acoounts` table has some columns you must introduce their
        // names like this (if the properties' names are different from columns' names)    
        entity.Property(e => e.Id)
              .HasColumnName("id");
        entity.Property(e => e.FirstName)
              .HasColumnName("first_name");
        entity.Property(e => e.LastName)
              .HasColumnName("last_name");
    });
    
    // Define the table `users`

    modelBuilder.Entity<User>(entity => {
        entity.ToTable("users");

        entity.HasIndex(e => e.Id)
           .HasName("users_account_id_foreign");

        entity.Property(e => e.Id)
           .HasColumnName("id")
           .HasColumnType("bigint(20) unsigned");

       entity.HasOne(d => d.Account)
           .WithOne(p => p.Users)
           .HasForeignKey<User>(d => d.Id)
           .HasConstraintName("users_account_id_foreign");
        
    });

}

The Add-Migration process compares two IModel instances, one from your context's OnModelCreating the other compiled into your assembly and loaded from the IMigrationsAssembly service.

The MigrationsAssembly implementation should only consider model snapshots and migrations with a matching DbContextAttribute.

If you are seeing migration operations that you didn't expect, then I have to wonder what your project looked like before you created two contexts. Do you have a generated ModelSnapshot, with a mismatched [DbContext] attribute?

Related