I have .NET Core 2 project in Visual Studio 2017. I am trying to add (Postgresql) database connection. Here is a code:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext(options =>
options.UseNpgsql(Configuration.GetConnectionString("DefaultConnection")));
// Add framework services.
services.AddMvc();
}
But compiler complains with this message:
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?)
I installed NuGet package Npgsql. I also tried to install NuGet package EntityFramework, but I'm receiving error:
Package restore failed. Rolling back package changes for 'MyProject'.
Is this the root of my problem? Should I install some other library?
On this question procedures AddEntityFramework() and AddEntityFrameworkNpgsql() are used, but those two are also not recognized by compiler in my project.
Make sure you installed related NuGet packages with the right version for example
Microsoft.EntityFrameworkCore v3
and are using the right namespace such as
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
I installed Npgsql.EntityFrameworkCore.PostgreSQL and that resolved my issue. I also used Danijel's suggestion:
services.AddDbContext<ClassDbContextName>(options =>
options.UseNpgsql(Configuration.GetConnectionString("DefaultConnection")));
Adding using Microsoft.Extensions.DependencyInjection fixed this issue for me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With