c# - 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
}
如文档中所述..
如果您需要一个连接字符串来运行迁移,那么对于那些没有连接字符串的情况(从用户帐户获取连接字符串的租户数据库),您如何运行初始迁移?
您是否创建了一个虚拟连接字符串来创建迁移..对我来说似乎很狡猾。我希望对此有一些意见。
解决方案
您可以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
推荐阅读
- macros - 从 Base 扩展 `@show`
- python - 将多索引熊猫数据框渲染为 html 时如何去除多余的单元格?
- sumologic - 您如何在 Sumo Logic 中执行相当于 SQL UNION 的操作?
- java - 生成新的游戏窗口
- java - C# Websocket 和 ECDHE 密码的问题
- python - 如何使用 nbconvert 将交互式 Jupyter 笔记本转换为 html
- google-apps-script - 函数错误:范围的起始行太小
- groovy - groovy.lang.MIssingPropertyException:没有这样的属性:类的testRunner:
- go - golang “go get” 拉取大量依赖项。即使尝试 go get -d ./... 失败并说它需要更多依赖项
- c - 如何将二进制转换为 ASCII