我有一个 ASP.NET Core 应用程序,我拥有的只是 DataContext
,我没有实现 IDesignTimeDbContextFactory
。
public class DataContext : DbContext, IUnitOfWork
{...}
有了它,我可以执行Add-Migration
、Update-Database
和Script-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 theDbContext
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 aCreateHostBuilder
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/