DbContext.OnConfiguring not getting called and behaving weird in Asp.net core

asp.net-core asp.net-mvc entity-framework-core

Question

In my asp.net core project i have a ReadingContext class derived from DbContext. According to documentation OnConfiguring should be called for every instance of DbContext that is created.

But in my case it is only called when i inspect the instance while debugging. I have a breakpoint inside OnConfiguring but it is not hit even when the method is called.

OnConfiguring method. OnConfiguring method .

Instance created but OnConfiguring not called yet Instance created

.

OnConfiguring called on looking into the object but it's breakpoint didn't hit. OnConfiguring called

1
1
8/20/2016 9:10:45 PM

Accepted Answer

According to documentation OnConfiguring should be called for every instance of DbContext that is created.

I don't know which documentation you refer to, but I'm sure it doesn't say that OnConfiguring runs when the context is created. Because it doesn't. It runs whenever a context instance is actually used for the first time. That's why you see the method call as soon as you start inspecting the context in the debug view. When you pause on a breakpoint in the debugger, the debugger will never jump to another breakpoint, even when the code is hit.

Contexts are supposed to be created and disposed in large numbers. Therefore, creating a context must be as light-weight as possible. Its internal components are created by lazy initialization as much as possible.

3
4/18/2017 11:33:09 PM

Popular Answer

Just in case anyone else had this issue, I had to use an empty constructor to get OnConfiguring called:

public ReadingContext() : base()
{

}
protected override void OnConfiguring(DbContextOptionsBuilder  
optionsBuilder)
{
  var builder = new ConfigurationBuilder().AddJsonFile("appsettings.json", 
    optional: true, reloadOnChange: true);
  config = builder.Build();  
  optionsBuilder.UseSqlServer(config.GetConnectionString
    ("ReadingContextConnection"));
}


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow