Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AddDbContext not available in IServiceCollection in .NET Core

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.

like image 653
Uros Avatar asked Jul 11 '17 10:07

Uros


3 Answers

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;

like image 66
Bashir Momen Avatar answered Nov 18 '22 16:11

Bashir Momen


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")));
like image 25
Uros Avatar answered Nov 18 '22 16:11

Uros


Adding using Microsoft.Extensions.DependencyInjection fixed this issue for me.

like image 2
pwned555 Avatar answered Nov 18 '22 16:11

pwned555