Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET: Check if run from migration

I have some code in my ConfigureServices that fails when running a migration:

dotnet ef migrations list

I'm trying to add a Certificate but it can't find the file (it works when starting the project as a whole). So is there a way to do something like this:

if (!CurrentEnvironment.IsMigration()) {
    doMyStuffThatFailsInMigration()
}

That way I could keep my code as it is but just execute it when not running it in a migration.

Thanks

like image 591
moritzg Avatar asked May 18 '17 08:05

moritzg


2 Answers

My current solution to detecting if a migration has not occurred:

using System.Linq;
// app is of type IApplicationBuilder
// RegisteredDBContext is the DBContext I have dependency injected
using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
        {
            var context = serviceScope.ServiceProvider.GetService<RegisteredDBContext>();
            if (context.Database.GetPendingMigrations().Any())
            {
                var msg = "There are pending migrations application will not start. Make sure migrations are ran.";
                throw new InvalidProgramException(msg);
                // Instead of error throwing, other code could happen
            }
        }

This assumes that the migrations have been synced to the database already. If only EnsureDatabase has been called, then this approach does not work, because the migrations are all still pending.

There are other method options on the context.Database. GetMigrations and GetAppliedMigrations.

like image 84
Garry Polley Avatar answered Oct 11 '22 01:10

Garry Polley


Just set a static flag in the Main method (which is not called by the dotnet-ef tool):

public class Program
{
    public static bool IsStartedWithMain { get; private set; }

    public static void Main(string[] args)
    {
        IsStartedWithMain = true;
        ...
    }
}

and then check it when needed:

internal static void ConfigureServices(WebHostBuilderContext context, IServiceCollection services)
{
    if (Program.IsStartedWithMain)
    {
        // do stuff which must not be run upon using the dotnet-ef tool
    }
}
like image 10
Nikolai Koudelia Avatar answered Oct 11 '22 01:10

Nikolai Koudelia