c# - ASP.NET核心: Why do we need IDesignTimeDbContextFactory?

标签 c# .net-core entity-framework-core asp.net-core-6.0

我有一个 ASP.NET Core 应用程序,我拥有的只是 DataContext,我没有实现 IDesignTimeDbContextFactory

public class DataContext : DbContext, IUnitOfWork
{...}

有了它,我可以执行Add-MigrationUpdate-DatabaseScript-Migration

但是,我遇到了另一个项目,他们实现了 IDesignTimeDbContextFactory,提到这是为了生成迁移类。

public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<CodingBlastDbContext>
{
    public CodingBlastDbContext CreateDbContext(string[] args)
    {
        IConfigurationRoot configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json")
            .Build();

        var builder = new DbContextOptionsBuilder<CodingBlastDbContext>();

        var connectionString = configuration.GetConnectionString("DefaultConnection");

        builder.UseSqlServer(connectionString);

        return new CodingBlastDbContext(builder.Options);
    }
}

我想知道为什么需要这个?特别是第一个项目无需实现 IDesignTimeDbContextFactory..

最佳答案

Docs关于何时可以利用设计时工厂的一些解释:

A design-time factory can be especially useful if you need to configure the DbContext differently for design time than at run time, if the DbContext constructor takes additional parameters are not registered in DI, if you are not using DI at all, or if for some reason you prefer not to have a CreateHostBuilder method in your ASP.NET Core application's Main class.

我个人遇到的唯一用例是当DbContext被移动到一个单独的库中并且我们不想运行CreateHostBuilder来进行上下文设计时(启动涉及一些相对沉重的东西,我们不想调用它)。例如here .

关于c# - ASP.NET核心: Why do we need IDesignTimeDbContextFactory?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73336365/

相关文章:

entity-framework - 调用新的 DbContext 时,DbContextOptions 中的内容是什么?

c# - 在标签中显示整数

c# - 什么动词可以描述 C# 类与其属性之间的关系?

c# - 检查 IEnumerable<T> 是否有 5 个或更多匹配项

asp.net-mvc - 在 .NET Core 2.0 中使用 WCF 服务

asp.net-core - 防止 Kestrel 在端口使用时崩溃

c# - httpclient工厂连线可以重复使用吗

c# - 将 Entity Framework Core 3.1 与 ServiceProvider 中的 UseInMemoryDatabase 选项一起使用(范围生命周期)

entity-framework-core - Entity Framework 7保存更改

C# PdfSharp - 从 HTML 生成 PDF 的困难