本文介绍了您如何在dotnet Core中使用DBContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以可以说我只是创建一个帮助器类,需要从静态方法内部调用数据库。
没有给出与'ApplicationDbContext.ApplicationDbContext(DbContextOptions<
的所需形式参数
ApplicationDbContext>)''
'options'相对应的参数pre>
我似乎无法做到
公共静态bool IsKeyValid(字符串键)
{
var isValid = false;
if(!String.IsNullOrEmpty(key)){
isValid = new ApplicationDbContext()。Children.Any(x => x.Token == key);
}
返回isValid;
}
所以我知道我可以从控制器获取上下文并将其传递给我,但这是唯一的方法吗?
我很困惑,因为所有文档都说嘿,创建一个新的上下文,看看它有多容易
解决方案如果需要手动创建上下文,则可以如下所示进行配置
var options = new DbContextOptionsBuilder< ApplicationDbContext>();。
选项。UseSqlServer(Configuration.GetConnectionStringSecureValue( DefaultConnection));
_context =新的ApplicationDbContext(options.Options);
也请参见:
So lets say I just make a helper class and need to call the DB from inside a Static Method.
There is no argument given that corresponds to the required formal parameter 'options' of 'ApplicationDbContext.ApplicationDbContext(DbContextOptions< ApplicationDbContext>)'
I can't seem to just do
public static bool IsKeyValid(string key) { var isValid = false; if (!String.IsNullOrEmpty(key)) { isValid = new ApplicationDbContext().Children.Any(x => x.Token == key); } return isValid; }
So I know I can get my context from my controller and pass it in, but is that the only way?
I'm very confused because all the docs just kinda say "Hey, make a new context, look how easy it is"http://ef.readthedocs.io/en/latest/querying/basic.html#id3
Any help would be appreciated
解决方案If you need to create the context manually, then you can configure it as shown below.
var options = new DbContextOptionsBuilder<ApplicationDbContext>(); options.UseSqlServer(Configuration.GetConnectionStringSecureValue("DefaultConnection")); _context = new ApplicationDbContext(options.Options);
Please see this too : Configuring a DbContext
这篇关于您如何在dotnet Core中使用DBContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!