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);
serviceCollection.AddSingleton(context);
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.
As @kriss suggests, adding
.AddEntityFrameworkSqlServer()
to the service collection before the .AddDbContext()
did the trick.
Thanks Kriss!