Accepted answer

You are using dependency injection. services.AddDbContext is in charge of creating you an DbContext object. There is no point in having that using block because, by doing that, you are instancing a new ApplicationDbContext that doesn't have a connection string.

Write your method like this:

public HeaderModel GetHeaderInformation(ApplicationDbContext context)
    // the code inside your using block

and .Net will resolve the context via dependency injection.

Furthermore, a common practice is to have the DbContext as a private readonly atribute in your constructor class. So you may want do something like this:

public class MyConroller : Controller
    private readonly MyDbContext _context;

    public MyConroller(MyDbContext ctx)
        _context = ctx;

and just use the context atribute in your methods.


You should remove your parameterless constructor, because it is probably the one that is being called when a new instance is created by the DI. I know that for some people this was the problem, I hope it helps.

Related Articles