EF Core Database transation null when using AddDbContext dependency injection

.net c# dependency-injection entity-framework entity-framework-core


I'm trying to add a context to my servicecollection with:

serviceCollection.AddDbContext<MyContext>(options => options.UseSqlServer("My connection string"));

a little further I execute a query by getting an instance of the context:

var context = serviceProvider.GetService<MyContext>();
var user = context.Users.FirstOrDefault(u => u.UserName == userName);

Which throws the error:

System.NullReferenceException: 'Object reference not set to an instance of an object.'

Strangely the context nor the DbSet users is null. When I debug the provided context, I see that both properties ChangeTracker and Model on de context instance have thrown the following error:

'context.ChangeTracker' threw an exception of type 'System.InvalidOperationException'

When I replace AddDbContext with a AddSingleton with an instance made like this:

var optionBuilder = new DbContextOptionsBuilder<MyContext>().UseSqlServer("My connetion string");
var context = new MyContext(optionBuilder.Options);


everything works fine.

I'm using the Microsoft dependency in a .NET Framework 4.6.1 dll project, referenced by a .NET Core 2.1 Console application which simply executes the code in the dll.

4/6/2020 5:10:20 PM

Popular Answer

As @kriss suggests, adding


to the service collection before the .AddDbContext() did the trick.

Thanks Kriss!

4/7/2020 6:12:15 AM

Related Questions


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