你如何在dotnet Core中使用DBContext

时间:2016-08-26 15:51:40

标签: entity-framework asp.net-core

所以我想说我只是创建一个帮助类,需要从静态方法中调用数据库。

There is no argument given that corresponds to the required formal parameter 
'options' of 'ApplicationDbContext.ApplicationDbContext(DbContextOptions<‌​
ApplicationDbContext‌​>)' 

我似乎无法做到

    public static bool IsKeyValid(string key)
    {
        var isValid = false;

        if (!String.IsNullOrEmpty(key)) {
            isValid = new ApplicationDbContext().Children.Any(x => x.Token == key);
        }

        return isValid;
    }

所以我知道我可以从我的控制器获取我的上下文并将其传入,但这是唯一的方法吗?

我很困惑,因为所有的文档都有点说“嘿,做一个新的背景,看看它有多容易” http://ef.readthedocs.io/en/latest/querying/basic.html#id3

任何帮助将不胜感激

enter image description here

1 个答案:

答案 0 :(得分:2)

如果您需要手动创建上下文,则可以按如下所示对其进行配置。

var options = new DbContextOptionsBuilder<ApplicationDbContext>();
options.UseSqlServer(Configuration.GetConnectionStringSecureValue("DefaultConnection"));
_context = new ApplicationDbContext(options.Options); 

请同时查看:Configuring a DbContext

相关问题