小编fig*_*lot的帖子

使用配置调用“AddDbContext”,但上下文类型仅声明无参数构造函数

我在开发项目时遇到错误。

我的代码如下..

错误信息 :

System.ArgumentException:使用配置调用“AddDbContext”,但上下文类型“NoteDbContext”仅声明无参数构造函数。这意味着传递给“AddDbContext”的配置将永远不会被使用。如果配置传递给“AddDbContext”,则“NoteDbContext”应该声明一个接受 DbContextOptions 的构造函数,并且必须将其传递给 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; }
}
Run Code Online (Sandbox Code Playgroud)

ASP.Net 项目 - 启动

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

我搜索了这些错误的解决方案,但找不到。

asp.net dependency-injection dbcontext asp.net-core-mvc

4
推荐指数
1
解决办法
2924
查看次数