Пример #1
0
    protected async Task CreateInitialMigrationsAsync(ProjectBuildArgs projectArgs)
    {
        if (projectArgs.DatabaseProvider == DatabaseProvider.MongoDb)
        {
            return;
        }

        var  efCoreProjectPath = string.Empty;
        bool isLayeredTemplate;

        switch (projectArgs.TemplateName)
        {
        case AppTemplate.TemplateName:
        case AppProTemplate.TemplateName:
            efCoreProjectPath = Directory.GetFiles(projectArgs.OutputFolder, "*EntityFrameworkCore.csproj", SearchOption.AllDirectories).FirstOrDefault();
            isLayeredTemplate = true;
            break;

        case AppNoLayersTemplate.TemplateName:
        case AppNoLayersProTemplate.TemplateName:
            efCoreProjectPath = Directory.GetFiles(projectArgs.OutputFolder, "*.csproj", SearchOption.AllDirectories).FirstOrDefault();
            isLayeredTemplate = false;
            break;

        default:
            return;
        }

        if (string.IsNullOrWhiteSpace(efCoreProjectPath))
        {
            Logger.LogWarning("Couldn't find the project to create initial migrations!");
            return;
        }

        await EventBus.PublishAsync(new ProjectCreationProgressEvent
        {
            Message = "Creating the initial DB migration"
        }, false);

        await InitialMigrationCreator.CreateAsync(Path.GetDirectoryName(efCoreProjectPath), isLayeredTemplate);
    }
    public virtual async Task ExecuteAsync(CommandLineArgs commandLineArgs)
    {
        if (commandLineArgs.Target.IsNullOrEmpty())
        {
            throw new CliUsageException("DbMigrations folder path is missing!");
        }

        var dbMigrationsFolder = commandLineArgs.Target;

        var nolayers = commandLineArgs.Options.ContainsKey("nolayers");
        var dbMigratorProjectPath = GetDbMigratorProjectPath(dbMigrationsFolder);

        if (!nolayers && dbMigratorProjectPath == null)
        {
            throw new Exception("DbMigrator is not found!");
        }

        await DotnetEfToolManager.BeSureInstalledAsync();

        var migrationsCreatedSuccessfully = await _initialMigrationCreator.CreateAsync(commandLineArgs.Target, !nolayers);

        if (migrationsCreatedSuccessfully)
        {
            if (nolayers)
            {
                CmdHelper.RunCmd("dotnet run --migrate-database", Path.GetDirectoryName(Path.Combine(dbMigrationsFolder, "MyCompanyName.MyProjectName")));
            }
            else
            {
                CmdHelper.RunCmd("dotnet run", Path.GetDirectoryName(dbMigratorProjectPath));
            }
            await Task.CompletedTask;
        }
        else
        {
            var exceptionMsg = "Migrations failed! A migration command didn't run successfully.";

            Logger.LogError(exceptionMsg);
            throw new Exception(exceptionMsg);
        }
    }