Malik Kashmiri
Malik Kashmiri

Reputation: 5861

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

Detail

I am trying to create asp.net core application and use scaffold-dbcontext to generate class. when I run this app it shows me the error. I already follow some answer on stackoverflow with the same issue but mine remains. 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")));

    }

Error

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

Upvotes: 5

Views: 3566

Answers (1)

romy
romy

Reputation: 11

in appsetting.json file declare your connection string with name "DefaultConnection"

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

Upvotes: 1

Related Questions