首页 > 解决方案 > EF Core - 创建没有连接字符串的迁移

问题描述

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

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

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
}

文档中所述..

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

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

标签: c#entity-frameworkasp.net-coreentity-framework-coreentity-framework-migrations

解决方案


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

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

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

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


推荐阅读