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

C#Entity Framework.Net CoreEntity Framework-Core

C# Problem Overview


In the following console application (.Net core 2.0), the scaffold-dbcontext created the following DbContext

public partial class MyContext : DbContext
{
    public virtual DbSet<Tables> Tables { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured) { optionsBuilder.UseSqlServer(Program.Conn); }
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder) { .... }
}

In the Main() (static void Main(string[] args)), the following code

var services = new ServiceCollection();
var conn = configuration.GetConnectionString("MySource");
services.AddDbContext<MyContext>(o => o.UseSqlServer(conn)); // Error

got the following run-time 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

C# Solutions


Solution 1 - C#

As the error said it if you configure your MyContext through AddDbContext then you need too add a constructor that receive a parameter of type DbContextOptions<MyContext> into your MyContext class like below

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

If you don't do that, ASP.Net Core will not be able to inject the configuration you set with AddDbContext.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionca9163d9View Question on Stackoverflow
Solution 1 - C#CodeNotFoundView Answer on Stackoverflow