具有不同启动项目的 Ef 核心迁移

Ef core migration with different startup project

我有一个项目,我的 Azure 功能将作为 API 运行。 然后我有一个单独的“核心”项目,包括我的 efcore、dbcontext 和模型。

我在核心项目中添加了一个配置器 class,如下所示:

    public static IServiceCollection AddDatabaseContext(this IServiceCollection services, Action<DatabaseOptions> configureOptions)
{
    services.Configure(configureOptions);
    services.AddDbContextPool<SampleApiDbContext>((provider, options) =>
    {
        var dbOptions = provider.GetRequiredService<IOptionsMonitor<DatabaseOptions>>().CurrentValue;
        options.UseSqlServer(dbOptions.ConnectionString, b=> b.MigrationsAssembly("Dymak.SampleLibraryApi.Admin"));
    });

    return services;
}

还有我的初创公司 class 在 api 项目中。

public class Startup : FunctionsStartup
{
    public override void Configure(IFunctionsHostBuilder builder)
    {
        string sqlConnection = Environment.GetEnvironmentVariable("SqlConnectionString");

        builder.Services.AddDatabaseContext(options => 
        { 
            options.ConnectionString = sqlConnection; 
        });
    }
}

参考我的 dbcontext。

public class SampleApiDbContext : DbContext
{
    public SampleApiDbContext(DbContextOptions<SampleApiDbContext> options) : base(options)
    {

    }

    public SampleApiDbContext()
    {
    }

    public DbSet<Category> Categories { get; set; } = null!;
    public DbSet<Models.TagType> Types { get; set; } = null!;
    public DbSet<Tag> Tags { get; set; } = null!;
}

任何时候我运行命令

dotnet ef --startup-project ..\Dymak.SampleLibraryApi migrations add Initial

我收到以下错误消息

Unable to create an object of type 'SampleApiDbContext'. For different patterns.......

我还没有找到解决我的问题的办法,所以我希望这里有人知道。

您是否尝试在 ef migrations add 命令中引用您的目标(核心)项目?

dotnet ef --project <project-where-you-have-dbcontext> --startup-project ..\Dymak.SampleLibraryApi migrations add Initial

由于我使用的是 azure 函数,因此似乎无法执行此操作,因为 EntityFramework 迁移无法在 Azure 函数中自动发现我的迁移。

所以我不得不创建一个单独的 class,我在其中创建了一个 IDesignTime 工厂。 (在核心项目中)

public class SampleApiDbContextFactory : IDesignTimeDbContextFactory<SampleApiDbContext>
{
    public SampleApiDbContext CreateDbContext(string[] args)
    {
        var optionsBuilder = new DbContextOptionsBuilder<SampleApiDbContext>();
        optionsBuilder.UseSqlServer("random string");

        return new SampleApiDbContext(optionsBuilder.Options);
    }
} 

它确实解决了我的一些问题,但我似乎无法让它自动进行迁移。但这对我仍然有效。