AddDbContext在.NET Core中的IServiceCollection中不可用

Uro*_*ros 6 .net c# postgresql .net-core visual-studio-2017

我在Visual Studio 2017中有.NET Core 2项目.我正在尝试添加(Postgresql)数据库连接.这是一个代码:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext(options =>
        options.UseNpgsql(Configuration.GetConnectionString("DefaultConnection")));

    // Add framework services.
    services.AddMvc();
}
Run Code Online (Sandbox Code Playgroud)

但编译器抱怨这条消息:

IServiceCollection不包含'AddDbContext'的定义,并且没有可以找到接受类型'IServiceCollection'的第一个参数的扩展方法'AddDbContext'(你是否缺少using指令或汇编引用?)

我安装了NuGet包Npgsql.我也尝试安装NuGet包EntityFramework,但我收到错误:

包恢复失败.回滚"MyProject"的包更改.

这是我问题的根源吗?我应该安装一些其他库吗?

在这个问题上使用了 AddEntityFramework()和AddEntityFrameworkNpgsql()程序,但是我的项目中的编译器也无法识别这两个程序.

Bas*_*hir 17

确保你安装了正确版本的相关 NuGet 包,例如

Microsoft.EntityFrameworkCore v3

并且正在使用正确的命名空间,例如

使用 Microsoft.EntityFrameworkCore;

使用 Microsoft.Extensions.DependencyInjection;


Uro*_*ros 3

我安装了 Npgsql.EntityFrameworkCore.PostgreSQL 并解决了我的问题。我还使用了丹尼尔的建议:

services.AddDbContext<ClassDbContextName>(options =>
            options.UseNpgsql(Configuration.GetConnectionString("DefaultConnection")));
Run Code Online (Sandbox Code Playgroud)