EF Core - 创建没有连接字符串的迁移

si2*_*030 8 c# entity-framework entity-framework-core asp.net-core entity-framework-migrations

我一直在研究适合这个问题的多个问题、教程和示例。

如果我在创建第一个初始迁移时不知道我的连接字符串怎么办?鉴于我有机会在实例化上下文时设置连接字符串,例如:

var connection = @"Server=(localdb)\mssqllocaldb;Database=JobsLedgerDB;Trusted_Connection=True;ConnectRetryCount=0";
var optionsBuilder = new DbContextOptionsBuilder<BloggingContext>();
optionsBuilder.UseSqlServer(connection);

using (var context = new BloggingContext(optionsBuilder.Options))
{
  // do stuff
}
Run Code Online (Sandbox Code Playgroud)

文档中所述..

如果您需要一个连接字符串来运行迁移,那么对于那些没有连接字符串的情况(从用户帐户获取连接字符串的租户数据库),您如何运行初始迁移?

您是否创建了一个虚拟连接字符串来创建迁移.. 对我来说似乎很狡猾。我希望对此有一些意见。

Voč*_*čko 1

您可以IDesignTimeDbContextFactory在设计时实现它将代替您的主机构建器使用。UseSqlServer 现在具有无参数重载。

它看起来像这样,并且必须位于与数据库上下文相同的程序集中或启动项目中:

public class MyAppDbContextFactory: IDesignTimeDbContextFactory<MyAppDbContext>
{
    public MyAppDbContext CreateDbContext(string[] args)
    {
        var optionsBuilder = new DbContextOptionsBuilder<MyAppDbContext>();
        optionsBuilder.UseSqlServer();
            
        return new MyAppDbContext(optionsBuilder.Options);
    }
}
Run Code Online (Sandbox Code Playgroud)

更多详细信息可以在这里找到: https://learn.microsoft.com/en-us/ef/core/cli/dbcontext-creation ?tabs=dotnet-core-cli#from-a-design-time-factory