AddDbContext not available in IServiceCollection in .NET Core
我在Visual Studio 2017中具有.NET Core 2项目。我试图添加(Postgresql)数据库连接。这是代码:
1 2 3 4 5 6 7 8 | public void ConfigureServices(IServiceCollection services) { services.AddDbContext(options => options.UseNpgsql(Configuration.GetConnectionString("DefaultConnection"))); // Add framework services. services.AddMvc(); } |
但是编译器抱怨以下消息:
IServiceCollection does not contain a definition for 'AddDbContext'
and no extension method 'AddDbContext' accepting a first argument of
type 'IServiceCollection' could be found (are you missing a using
directive or an assembly reference?)
我安装了NuGet软件包Npgsql。我也尝试安装NuGet软件包EntityFramework,但收到错误消息:
打包还原失败。回滚\\'MyProject \\'的程序包更改。
这是我问题的根源吗?我应该安装其他库吗?
在这个问题上,使用了AddEntityFramework()和AddEntityFrameworkNpgsql()程序,但是在我的项目中编译器也无法识别这两个程序。
确保以正确的版本安装了相关的NuGet软件包,例如
Microsoft.EntityFrameworkCore v3
并使用正确的名称空间,例如
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
我安装了Npgsql.EntityFrameworkCore.PostgreSQL,这解决了我的问题。我也使用了Danijel的建议:
1 2 | services.AddDbContext<ClassDbContextName>(options => options.UseNpgsql(Configuration.GetConnectionString("DefaultConnection"))); |
试试这个
services.AddDbContext(options =>
options.UseNpgsql(Configuration.GetConnectionString(" DefaultConnection ")))
使用Microsoft.Extensions.DependencyInjection添加为我解决了此问题。
您能不能这样尝试
1 2 | services.AddDbContext<ClassDbContextName>(options => options.UseNpgsql(Configuration.GetConnectionString("DefaultConnection"))); |