22
schangxiang@126.com
2025-05-20 0ab314db5c1b0e87f671c382cc6509c13177ae0c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
using CMS.Plugin.PipeLineLems.Domain;
using CMS.Plugin.PipeLineLems.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;
 
namespace CMS.Plugin.PipeLineLems.MySQL;
 
/// <summary>
/// This class is needed for EF Core console commands
///  (like Add-Migration and Update-Database commands)
/// </summary>
public class CMSPluginDbContextFactory : IDesignTimeDbContextFactory<CMSPluginDbContext>
{
    /// <summary>
    /// Creates a new instance of a derived context.
    /// </summary>
    /// <param name="args">Arguments provided by the design-time service.</param>
    public CMSPluginDbContext CreateDbContext(string[] args)
    {
        CMSPluginEfCoreEntityExtensionMappings.Configure();
 
        var configuration = BuildConfiguration();
 
        var builder = new DbContextOptionsBuilder<CMSPluginDbContext>()
                .UseMySql(configuration.GetConnectionString("Default"), MySqlServerVersion.LatestSupportedServerVersion,  x => x.MigrationsHistoryTable(CMSPluginDbProperties.MigrationsHistoryTable, CMSPluginDbProperties.DbSchema));
 
        return new CMSPluginDbContext(builder.Options);
    }
 
    /// <summary>
    /// Builds the configuration.
    /// </summary>
    /// <returns></returns>
    private static IConfigurationRoot BuildConfiguration()
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(Path.Combine(Directory.GetCurrentDirectory(), "../CMS.Plugin.PipeLineLems.EntityFrameworkCore/"))
            .AddJsonFile("appsettings.json", optional: false);
 
        return builder.Build();
    }
}