19

I'm working in a project that uses EF Code First. I'm trying to use migration features. I don't want to use Package Console Manager. How can I execute the "Add-Migration" and "Update-Database" programmatically?

add-migration TestMigration01 -force

update-database

2 Answers 2

17

You have a couple of choices. You can use the dbmigrator class from within your code: http://romiller.com/2012/02/09/running-scripting-migrations-from-code/

Or you can use migrate.exe which is handy for running them in a build step, etc. https://msdn.microsoft.com/en-us/data/jj618307.aspx

Sign up to request clarification or add additional context in comments.

Comments

0

Solution for EF Core:

public static void AddMigration()
{
    var h1 = new OperationReportHandler(
        errorHandler: (x) =>
        {
            throw new Exception(x);
        },
        warningHandler: (x) => 
        {
            Debug.WriteLine($"Warn, {x}");
        });

    var reporter = new OperationReporter(h1);

    Assembly asm = asm; // your Assembly
    Assembly startupAsm = asm; // your Assembly

    var projName = "<project name here>";
    var subPath = $"Database\\_Migrations";

    string rootNS = projName; 
    string subNS = null; // overrides rootNS

    var solRoot = "<solution root here>";
    var projRoot = Path.Combine(solRoot.FullName, projName);

    var outputDir = Path.Combine(projRoot, subPath);

    var args = new string[0]; //  
    var nullable = false; // nullable Ref Types
    string language = null; // defaults to "C#"

    var sec = ((long)(DateTime.UtcNow - StartDate).TotalSeconds);
    var migrationName = $"M_{sec}"; // your Migration Name

    MigrationsOperations migrationsOperations = new MigrationsOperations(
        reporter,
        asm, startupAsm, projRoot, rootNS,
        language, nullable, args);

    var ctxType = typeof(DbContextCreator).FullName; // your ContextType here

    MigrationFiles migrationFiles =
        migrationsOperations.AddMigration(migrationName, outputDir, ctxType, snapshotNS);
}

private static DateTime StartDate = new DateTime(2024, 04, 01);

Install the Nuget for Microsoft.EntityFrameworkCore.Design.
Then adjust the .csproj

<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.3">
  <PrivateAssets>all</PrivateAssets>
  <IncludeAssets></IncludeAssets>
</PackageReference>

You have to clear IncludeAssets to use the internal types of Microsoft.EntityFrameworkCore.Design.


I tried the code and it generates the same files as Package Manager Console:

Add-Migration -OutputDir Database\_Migrations -Context DbContextCreator

Update Database is just:

ctx.Database.Migrate();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.