Entity Framework Core 2.2 : Disable migrations for specific entities

Is there a proper way to handle this scenario?

Editing the Migration Code is a proper way to handle this scenario.

Alternatively, you could create one DbContext with Migrations containing only the Entities mapped to Tables you want to manage using Migrations. Then create another DbContext with all the Entities which is used to read and write to the database.

Note here that your Migration Context may lack Navigation Properties, containing only the corresponding Foreign Key Properties if you don't want to add real Foreign Keys in the database refering to tables not controlled by your Migrations.


You can ignore the entity if the entity builder is called after Add-Migration operation by examining the command line arguments;

public void Configure(EntityTypeBuilder<YourEntity> builder)
{
    //all properties to be mapped...

    //ignored when adding a new migration
    builder.HasOne(p => p.EntityDetail)
        .WithOne()
        .HasForeignKey<Entity>(x => x.Id)
        .IsRequired(false);

    if (MigrationHelper.IsMigrationOperationExecuting())
        builder.Ignore(x => x.EntityDetail);
}

public static class MigrationHelper
{
    public static bool IsMigrationOperationExecuting()
    {
        var commandLineArguments = Environment.GetCommandLineArgs();
        string[] orderedMigrationArguments = { "migrations", "add" };

        for (var i = 0; i <= commandLineArguments.Length - orderedMigrationArguments.Length; i++)
        {
            if (commandLineArguments.Skip(i).Take(orderedMigrationArguments.Length).SequenceEqual(orderedMigrationArguments))
                return true;
        }

        return false;
    }
}