My DbSet is required. I’d like to create test using InMemoryDatabase. However when I instantiate context I’m getting an error
Error (active) CS9035 Required member 'TestContext.Users' must be set in the object initializer or attribute constructor.
Below my code:
public class TestContext : DbContext
{
public virtual required DbSet<User> Users { get; set; }
public TestContext(DbContextOptions<TestContext> options) : base(options)
{
}
}
public class UserTests
{
public UserTests()
{
var options = new DbContextOptionsBuilder<TestContext>()
.UseInMemoryDatabase(Guid.NewGuid().ToString())
.Options;
TestContext testContext = new TestContext(options);
}
}
I tried to set Users property using initializer like this:
new TestContext(options) { Users = null}
but of course it sets DbSet to null which is not what I want to achieve. I also inherited abstract class DbSet but then I’d need to implement this class and I want to avoid that. I also tried to inherit Context but inherited properties also need to be required.
Is it a way to instantiate context without explicitly setting DbSets (please note that I’d like to keep required for DbSets, I also don’t want to use any mocking frameworks)?