如何在 EF Core 中实例化 DbContext [英] How to instantiate a DbContext in EF Core

查看:50
本文介绍了如何在 EF Core 中实例化 DbContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我也设置了 .net 核心项目和数据库上下文.但是由于这个错误,我还不能开始使用 dbContext-

I have setup .net core project and db context also. But i cant start using dbContext yet due this error-

"没有给出与所需形式相对应的参数参数'选项'"

"there is no argument given that corresponds to the required formal parameter 'options'"

控制器:

public IActionResult Index()
{
    using (var db = new BlexzWebDb())
    {

    }
    return View();
}

数据库上下文代码:

public class BlexzWebDb : DbContext
{
    public BlexzWebDb(DbContextOptions<BlexzWebDb> options)
       : base(options)
    { }

    public DbSet<User> Users { get; set; }
    public DbSet<Role> Roles { get; set; }
    public DbSet<AssignedRole> AssignedRoles { get; set; }

}

附上错误图片.该问题的可能解决方法是什么?提前致谢

error picture attached. Whats the possible fix for that issue? Thanks in advance

推荐答案

注意


在撰写本文时,EF Core 与依赖注入框架的使用并不像现在这样广为人知.这个答案从 DI 的角度回答了这个问题,这在当时帮助了 OP.

Note


At the time of writing the use of EF Core with the Dependency injection framework wasn't as known as it is now. This answers gives answer to the question from a DI perspective, which at the time, helped out OP.

另一个答案为您提供了一种使用 new 运算符实例化 DbContext 的常规方法.

The other answer provides you a conventional way to instantiate the DbContext using the new operator.

在应用程序配置期间注册 DbContext:

Register the DbContext during application configuration:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContextPool<BlexzWebDb>(options => 
           options.UseSqlServer(Configuration.GetConnectionString("BlexzWebConnection")));
}

并使用 DI 框架检索它:

and use the DI framework to retrieve it:

public class SomeController : Controller
{
    private readonly BlexzWebDb _db;

    //the framework handles this
    public SomeController(BlexzWebDb db)
    {
        _db = db;
    }
}

选项 2

如果您正在寻找使用 IOptions 的设计时 IdentityDbContext,请参阅:从另一个项目添加对 ApiAuthorizationDbContext 的迁移 - EF Core

Option 2

If you are looking for a design-time IdentityDbContext using IOptions<OperationalStoreOptions>, see: Add migration for ApiAuthorizationDbContext from another project - EF Core

或使用 new 运算符并提供详​​细信息,请参阅@Qamar Zaman 的回答以了解详细信息.

Or use the new operator and provide the details, see @Qamar Zaman's answer for details.

在 EF Core 中,通常将一些 DbContextOptions 传递给构造函数.

In EF Core it's common to pass some DbContextOptions to the constructor.

所以一般来说,构造函数看起来像这样:

So in general, a constructor looks like this:

public BlexzWebDb(DbContextOptions<BlexzWebDb> options) : base(options)

正如你在那里看到的,没有无参数构造函数形式的有效重载:

As you can see there, there is no valid overload in the form of a parameter-less constructor:

因此,这不起作用:

using (var db = new BlexzWebDb())

显然,您可以在构造函数中传入一个 Option 对象,但还有一种替代方法.所以,

Obviously, you can pass in an Option object in the constructor but there is an alternative. So,

代替

示例:您将在某处注册您的 dbcontext,(Startup.cs):

Example: somewhere you will register your dbcontext, (Startup.cs):

//typical configuration part of .net core
public void ConfigureServices(IServiceCollection services)
{
    //some mvc 
    services.AddMvc();
  
    //hey, options! 
    services.AddDbContextPool<BlexzWebDb>(options => 
           options.UseSqlServer(Configuration.GetConnectionString("BlexzWebConnection")));
    //...etc

现在注册部分已经完成,您可以从框架中检索您的上下文.例如:通过控制器中的构造函数反转控制:

Now the registering part is done, you can retrieve your context from the framework. E.g.: inversion of control through a constructor in your controller:

public class SomeController : Controller
{
    private readonly BlexzWebDb _db;

    //the framework handles this
    public SomeController(BlexzWebDb db)
    {
        _db = db;
    }

    //etc.


为什么?

那么,为什么不直接提供参数和 new 呢?

new 的使用没有任何问题 - 在很多情况下它效果最好.

There is nothing wrong with the use of new - there are a lot of scenario's in which it works best.

但是,控制反转被认为是一种很好的做法.在执行 asp dotnet core 时,您可能会经常使用它,因为大多数库都提供了使用它的扩展方法.如果您不熟悉它,并且您的研究允许;你一定要试一试.

But, Inversion Of Control is considered to be a good practice. When doing asp dotnet core you're likely to use it quite often because most libraries provide extension methods to use it. If you are not familiar with it, and your research allow it; you should definitely give it a try.

因此,我不会提供只是一种实例化"对象的方法,而是尝试让您进入这条轨道 - 与框架内联.它会为您节省一些麻烦.此外,否则使用激活器的 CreateInstance" 将与答案一样有效;-)

Therefore, instead of providing "just a way to instantiate" the object, I'll try to get you onto this track - inline with the framework. It will save you some hassle afterwards. Besides, otherwise "use an activator's CreateInstance" would just be as valid as an answer ;-)

一些链接:

这篇关于如何在 EF Core 中实例化 DbContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆