[英]How can I create a database on the fly with .NET Core EF
I'm having an issue with dotnet ef
.我遇到了
dotnet ef
的问题。 I'm trying to create a new database for every subdomain encountered.我正在尝试为遇到的每个子域创建一个新数据库。 I've learned I can use the
_context.Database.Migrate()
here, but it seems it's only possible in the Startup & Program classes.我知道我可以在这里使用
_context.Database.Migrate()
,但它似乎只能在 Startup & Program 类中使用。
How can I do this when the program is running already?当程序已经运行时,我该怎么做? Since I can only get the subdomain when the app is running
因为我只能在应用程序运行时获取子域
Here's what I've tried:这是我尝试过的:
// Db Context
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
// _ecosystemServices.GetSubdomain gets the domain
var subdomain = _ecosystemServices.GetSubDomain(_accessor);
// _ecosystemServices.GetConnectionString returns the appropriate connection string based on the subdomain
optionsBuilder.UseSqlServer(_ecosystemServices.GetConnectionString(subdomain));
// Attempting to create the database
_context.Database.Migrate();
}
But this doesn't work and I get a circular dependency error.但这不起作用,我得到一个循环依赖错误。 What should I do?
我应该怎么办?
Thanks in advance.提前致谢。
With EF Core you can use one of使用 EF Core,您可以使用以下之一
context.Database.Migrate()
or或者
context.Database.EnsureCreated(),
where context
is DbContext
.其中
context
是DbContext
。
Where you call any of these depends on the logic of your app, but in OnConfiguring()
is definitely not the right place since when database has to be created EF first creates the model and therefore calls OnConfiguring()
.您在哪里调用这些取决于您的应用程序的逻辑,但在
OnConfiguring()
绝对不是正确的位置,因为当必须创建数据库时,EF 首先创建 model 并因此调用OnConfiguring()
。 Hence you should get stack overflow message.因此,您应该收到堆栈溢出消息。
As of circular dependency I cannot tell but either the C# compiler is too smart and translates possible stack overflow to circular dependency (which I doubt, frankly), or the source of the error comes from somewhere else.至于循环依赖,我无法判断,但 C# 编译器太聪明了,会将可能的堆栈溢出转换为循环依赖(坦率地说,我对此表示怀疑),或者错误的根源来自其他地方。
You should be aware however, of the differences between Migrate()
and EnsureCreatd()
.但是,您应该注意
Migrate()
和EnsureCreatd()
之间的区别。 The second one does not apply the migrations in your code.第二个不会在您的代码中应用迁移。 Here's an answer by Rowan Miller to a similar question about both methods in Github :
这是Rowan Miller对Github中两种方法的类似问题的回答:
You would either call EnsureCreated() or Migrate().
您可以调用 EnsureCreated() 或 Migrate()。 EnsureCreated() is an alternative that completely skips the migrations pipeline and just creates a database that matches you current model.
EnsureCreated() 是一种替代方法,它完全跳过迁移管道,只创建一个与您当前的 model 匹配的数据库。 It's good for unit testing or very early prototyping, when you are happy just to delete and re-create the database when the model changes.
当 model 发生变化时,当您很高兴删除并重新创建数据库时,这对于单元测试或非常早期的原型设计很有用。
You can just replace all your code with db.Database.Migrate();
您可以将所有代码替换为 db.Database.Migrate();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.