0

I have a minimal api project that works with a single DBContext for one SqlServer db that is in a separate EFCore project. I've added a second GFContext to the EFCore project. When I attempt to access an entity in the new GFContext, the

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)

is never called and I get the: InvalidOperationException: No database provider has been configured ... error message.

The GFContext module includes:

public GFContext(DbContextOptions<GFContext> options) : base(options)

How do I get the 2nd Context to call the overrided OnConfiguring?

The only solutions I found are for asp.net and dbcontext factories.

Thanks ... Abbott

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
BedfordNYGuy
  • 383
  • 2
  • 9
  • Can you please show how do you register both contexts? Also full [mre] would be great. – Guru Stron Feb 03 '23 at 10:12
  • TI do not know how the wiring was done for DBContext (it was automatic with my scaffolding). When I scaffolded GFContext, the wiring was not done. In program.cs line 50 I added {builder.Services.AddDbContext();}. But that did not work. The reproducible example is at https://github.com/AbbottF/KBOInventoryApiMirror. I id not want to rip out authentication so you have to log in first. uid piggley pw wiggley. It works at: GetInventoryTickets It fails at: GetGFCategories Thanks - Abbott – BedfordNYGuy Feb 04 '23 at 17:54

1 Answers1

0

The problem which leads to the problem is the following: GFContext which has entities and stuff and GFContext which has OnConfiguring method override are different classes because they are in different namespaces (which are case sensitive):

namespace KBO.EFcore.GFXContext;
namespace KBO.EFCore.GFXContext;

Fix the casing.

Few extra notes/recommendations:

  1. Usually it is better to follow the idiomatic approach with DI - do not instantiate the contexts manually use dependency injection. Instead of static services (like GypsysFindsHandler) create an instance ones, register them in the DI and resolve in handlers (i.e. app.MapGet("/GetGFCategories", (SomeService serv) => serv.DoSomething)
  2. Use idiomatic approach to register the context (see the docs), i.e. instead of overriding OnConfiguring and calling UseSqlServer there just read the config in the Program.cs and use it to register the context - builder.Services.AddDbContext<GFContext>(opts => opts.UseSqlServer(connStringFromCtx));
  3. Use async calls to the database i.e. _db.Categories.___.ToList() -> await _db.Categories.___.ToListAsync()
Guru Stron
  • 102,774
  • 10
  • 95
  • 132
  • 1
    Thanks. My dyslexia got the best of me. I now have a logon issue (which is all on me). I will follow the idiomatic approach with DI (requires reading on my part). I've used the override to support my moving debugging between several machines. Once in production I'll follow thru with that. I will move to async calls (lasy on my part). – BedfordNYGuy Feb 05 '23 at 16:42