使用配置调用AddDbContext,但是上下文类型' ContextClass'只声明一个无参数构造函数?

时间:2018-04-06 11:18:29

标签: c# asp.net-core ef-core-2.0

详细

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

MyContext

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) { .... }
}

Startup.cs

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")));

    }

错误

  

使用配置调用AddDbContext,但是上下文类型&#39; MyContext&#39;只声明一个无参数构造函数。这意味着永远不会使用传递给AddDbContext的配置。如果配置传递给AddDbContext,那么&#39; MyContext&#39;应该声明一个接受DbContextOptions的构造函数,并且必须将它传递给DbContext的基础构造函数。

1 个答案:

答案 0 :(得分:1)

appsetting.json文件中的

声明名称为“ DefaultConnection”的连接字符串

"Data": {
   "DefaultConnection": "Data Source=(local); Initial Catalog=DBname; Integrated Security=True"
}