AddDbContext 是通过配置调用的,但是上下文类型“ContextClass”只声明了一个无参数的构造函数?

Mal*_*iri 5 c# asp.net-core ef-core-2.0

细节

我正在尝试创建 asp.net 核心应用程序并使用 scaffold-dbcontext 生成类。当我运行这个应用程序时,它会向我显示错误。我已经按照相同的问题在 stackoverflow 上找到了一些答案,但我的仍然存在。

我的上下文

public partial class MyContext: DbContext
{

    public MyContext(DbContextOptions<MyContext> options) : base(options)
    {
    }


    public virtual DbSet<Answer> Answer { get; set; }
    public virtual DbSet<Attachment> Attachment { get; set; }
    public virtual DbSet<Category> Category { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {

        if (!optionsBuilder.IsConfigured)
        {
            optionsBuilder.UseSqlServer(@"Server=.;Database=MyContext;Trusted_Connection=True;");
        }
    protected override void OnModelCreating(ModelBuilder modelBuilder) { .... }
}
Run Code Online (Sandbox Code Playgroud)

启动文件

public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();

        services.AddMvc()
       .AddJsonOptions(options =>
           options.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.All);

        services.AddDbContext<MyContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

    }
Run Code Online (Sandbox Code Playgroud)

错误

AddDbContext 是通过配置调用的,但上下文类型“MyContext”仅声明了一个无参数构造函数。这意味着永远不会使用传递给 AddDbContext 的配置。如果将配置传递给 AddDbContext,则“MyContext”应声明一个接受 DbContextOptions 的构造函数,并且必须将其传递给 DbContext 的基本构造函数。

小智 1

在 appsetting.json 文件中声明名为“DefaultConnection”的连接字符串

"Data": {
   "DefaultConnection": "Data Source=(local); Initial Catalog=DBname; Integrated Security=True"
}
Run Code Online (Sandbox Code Playgroud)