Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 525
Malik Kashmiri Avatar asked Nov 07 '22 08:11

Malik Kashmiri


1 Answers

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

"Data": {
   "DefaultConnection": "Data Source=(local); Initial Catalog=DBname; Integrated Security=True"
}
like image 175
romy Avatar answered Nov 15 '22 07:11

romy