[英]How to apply EF Core DB schema from a shared class library NuGet package
Let's say I have a class that extends DBContext (hereby called DBContext for simplicity) defined in a shared library plus an extension method to simplify adding this DBContext to dependency injection (given a configuration variable, it will generate a connection string to the database).假设我有一个 class,它扩展了共享库中定义的 DBContext(为简单起见,在此称为 DBContext),加上一个扩展方法来简化将此 DBContext 添加到依赖项注入(给定一个配置变量,它将生成一个连接字符串到数据库)。
How would I go about applying the database schema?我 go 如何应用数据库架构? From the shared library?
来自共享库? From a binary that consumes this library?
来自使用该库的二进制文件?
It's my understanding that when you apply a schema to a database a migrations folder is created and I want one canonical place where these migrations go.据我了解,当您将模式应用于数据库时,会创建一个迁移文件夹,我想要一个规范的位置来存放这些迁移 go。
If I run do.net ef database update
from the shared library, how does it know where the database is if I'm not providing configuration?如果我从共享库运行
do.net ef database update
,如果我不提供配置,它如何知道数据库在哪里? Where would I provide configuration (like which database server and what credentials)我将在哪里提供配置(比如哪个数据库服务器和什么凭据)
This shared library will likely be used by many consumers, so having migration scripts on each project sounds like a bad idea.这个共享库可能会被许多消费者使用,因此在每个项目上都有迁移脚本听起来不是个好主意。 Any suggestions?
有什么建议么?
Place the Connection String inside configuration for your Startup project (appsettings.json or other) and pass it to your extension method in your library.将连接字符串放入启动项目(appsettings.json 或其他)的配置中,并将其传递给库中的扩展方法。
Leave the Migrations in the library project with the DbContext
.将 Migrations 保留在带有
DbContext
的库项目中。 When you run do.net ef database update
you can provide separate --project
(the project with your DbContext and Migrations) and --startup-project
(the project that actually consumes your library) options.当您运行
do.net ef database update
时,您可以提供单独的--project
(带有 DbContext 和迁移的项目)和--startup-project
(实际使用您的库的项目)选项。
https://learn.microsoft.com/en-us/ef/core/cli/do.net#using-the-tools https://learn.microsoft.com/en-us/ef/core/cli/do.net#using-the-tools
The startup project is the one that the tools build and run.
启动项目是工具构建和运行的项目。 The tools have to execute application code at design time to get information about the project, such as the database connection string and the configuration of the model. By default, the project in the current directory is the startup project.
这些工具必须在设计时执行应用程序代码以获取有关项目的信息,例如数据库连接字符串和 model 的配置。默认情况下,当前目录中的项目是启动项目。 You can specify a different project as startup project by using the --startup-project option.
您可以使用 --startup-project 选项将不同的项目指定为启动项目。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.