简体   繁体   English

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

[英]EF Core - Create a migration without connection string

I have been ranging across multiple questions, tutorials and examples for something that fits this problem.我一直在研究适合这个问题的多个问题、教程和示例。

What if I don't know my connection string at the time I want to create my first initial migration?如果我在创建第一个初始迁移时不知道我的连接字符串怎么办? Given I am given the opportunity to set the connection string at the time of instantiating context eg:鉴于我有机会在实例化上下文时设置连接字符串,例如:

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
}

As described in the docs ..文档中所述..

If you need to have a connection string to run migrations then for those situations where you don't have one (Tenant database where you get a connection string from a user account) how do you run an initial migration??如果您需要一个连接字符串来运行迁移,那么对于那些没有连接字符串的情况(从用户帐户获取连接字符串的租户数据库),您如何运行初始迁移?

Do you create a dummy connection string to create the migration.. seems dodgy to me.您是否创建了一个虚拟连接字符串来创建迁移.. 对我来说似乎很狡猾。 I would love some input on this.我希望对此有一些意见。

You can implement IDesignTimeDbContextFactory that will be used instead your host builder in the design time.您可以实现IDesignTimeDbContextFactory ,它将在设计时代替您的主机构建器使用。 UseSqlServer now has a parameterless overload. UseSqlServer 现在具有无参数重载。

It will look like this and has to be in the same assembly as the db context or in the startup project:它看起来像这样,并且必须与 db 上下文或启动项目在同一个程序集中:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM