从dbcontext EF核心读取连接字符串6

发布于 2025-02-11 06:54:28 字数 801 浏览 4 评论 0原文

我正在使用ef6,并且已经生成了dbcontext,但是vs建议我不要将连接字符串在同一代码中,所以我将其传递给了appsettings.json。知道如何做到这一点,我的dbcontext类知道已经设置了连接字符串。

首先,我从我的dbcontext类中删除连接字符串配置:

”在此处输入图像描述”

然后y在程序类中添加我的配置:

”

但是当我执行数据库时,我以下例外:

没有为此DBContext配置数据库提供商。可以通过覆盖“ dbcontext.onconfiguring”方法或在应用程序服务提供商上使用“ AddDbContext”来配置提供商。如果使用了“ addDbContext”,则还确保您的dbcontext类型

如何使我的DBContext类知道正在读取连接字符串?我应该在配置方法中放置什么?

I am using EF6 and I have generated my dbcontext, but vs recommends me not to have the connection string within the same code, so I passed it to the appsettings.json and I am reading it from my Program.cs but I don't know how to do that my DBContext class knows that the connection string has already been set.

First, i remove the connection string config from OnConfiguring method from my dbcontext class:

enter image description here

Then y add my config in Program class:

enter image description here

but when i execute a database call it throws me the following exception:

No database provider has been configured for this DbContext. A provider can be configured by overriding the 'DbContext.OnConfiguring' method or by using 'AddDbContext' on the application service provider. If 'AddDbContext' is used, then also ensure that your DbContext type

How do I make my DBContext class know that the connection string is being read? What should I put in my OnConfiguring method?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

画尸师 2025-02-18 06:54:28

首先,您需要将以下代码行传递到on ConconFiguring方法:

base.OnConfiguring(optionsBuilder);

dbContextoptions实例的情况下,可能或可能不会将其传递给构造函数,您可以使用dbContextOptionsBuilder.isconfigured来确定是否已经设置了选项,并在on Configuring(dbcontextoptionsbuilder)中跳过某些或全部逻辑。

First of all, you need to pass the following line of code into your OnConfiguring method:

base.OnConfiguring(optionsBuilder);

In situations where an instance of DbContextOptions may or may not have been passed to the constructor, you can use DbContextOptionsBuilder.IsConfigured to determine if the options have already been set, and skip some or all of the logic in OnConfiguring(DbContextOptionsBuilder) .

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文