Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'AddDbContext' was called with configuration, but the context type only declares a parameterless constructor

I got an error while developing the project.

My codes are below..

Error Message :

System.ArgumentException: ''AddDbContext' was called with configuration, but the context type 'NoteDbContext' only declares a parameterless constructor. This means that the configuration passed to 'AddDbContext' will never be used. If configuration is passed to 'AddDbContext', then 'NoteDbContext' should declare a constructor that accepts a DbContextOptions and must pass it to the base constructor for DbContext.'

DbContext

public class NoteDbContext : DbContext
{
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        base.OnConfiguring(optionsBuilder);
        optionsBuilder.UseSqlServer(
            "Server=DESKTOP-BELVBNK\\SQLEXPRESS;" +
            "DataBase=NoteAppDB;Trusted_Connection=True;");
    }

    public DbSet<Entities.Note> Notes { get; set; }
}

ASP.Net Project - Startup

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews();
    services.AddDbContext<NoteDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("NoteAppDB")));
}

I searched for the solution of these errors, but could not find it.

like image 546
fighterpilot Avatar asked Oct 23 '25 22:10

fighterpilot


1 Answers

When you register a DbContext with AddDbContext you need to have a special constructor, like:

public NoteDbContext(DbContextOptions options) : base(options) {}

This is required. See https://learn.microsoft.com/en-us/ef/core/dbcontext-configuration/.

like image 121
Ricardo Peres Avatar answered Oct 27 '25 01:10

Ricardo Peres



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!