我正在尝试使用Visual Studio脚手架新的剃须刀视图。我选择一个模板,我的模型和 dbContext
,然后获取下面显示的错误消息。
值得注意的事情。我的模型,我的 dbContext
和我的网站都在不同的项目中。从下面的消息中,我正在使用 adddbContext
,并且有一个构造函数,该构造函数接受 dbContextOptions< tcontext>
parameter。
我在博客文章上读了一条评论,即问题是因为我的上下文在另一个项目中。该注释引用了有关将配置
注入 dbcontext
的需要的内容以获取连接字符串并在 on Conconfiguring
覆盖中手动添加。
如果这是正确的或如何进行设置,我找不到任何示例。任何帮助将不胜感激。
EDIT:
从上面提到的博客评论中测试理论,我将本节添加到了我的dbcontext中。 ConnectionsTring
是一个硬编码的字符串常数,其中包含我的连接信息。这确实有效并让我脚手架,因此问题仍然存在。如何将此连接字符串注入我的dbcontext以允许脚手架工作?
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer(ConnectionString);
}
else
{
base.OnConfiguring(optionsBuilder);
}
}
编辑:因此,在进行此更改之后,我检查了代码,并让另一个开发人员选择了它。似乎上面的本节只需要在那里即可允许脚手架工作。他从未将连接字符串更改为他的环境。他不再遇到错误的错误。
I'm trying to scaffold a new razor view using Visual Studio. I select a template, my model and my DbContext
, then I get the error message shown below.
Things to note. My models, my DbContext
and my website are all in different projects. From the message below I am using AddDbContext
and I have a constructor that accepts a DbContextOptions<TContext>
parameter.
I read a comment on a blog post that the issue is because my context is in another project. The comment referenced something about the need to inject the Configuration
into the DbContext
to get the connection string and manually add it in the OnConfiguring
override.
I can't find any examples if this is correct or how to set it up. Any help would be appreciated.
EDIT:
Testing out the theory from the blog comment I mentioned above, I added this section into my DbContext. ConnectionString
is a hardcoded string constant with my connection information. This does work and allow me to scaffold, so the question still remains. How can I inject this connection string into my DbContext to allow the scaffolding to work?
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer(ConnectionString);
}
else
{
base.OnConfiguring(optionsBuilder);
}
}
EDIT: So after making this change, I checked in the code and had another developer pick it up. It appears this section above just needs to be there to allow scaffolding to work. He never changed the connection string to point to his environment. He no longer got the error above it just worked.
发布评论
评论(1)
我不确定实际问题是什么,但似乎我们在设计时创建 DbContext 时遇到了问题。我手动添加了下面的代码,现在可以使用了。这只是一个临时解决方案。
参考:https://stackoverflow.com/a/70559350
I am not sure about what is the actual problem but it seems like we were having problems creating DbContext at design time. I manually added the code below and it's working now. It's just a temporary solution tho.
Reference: https://stackoverflow.com/a/70559350