为同样依赖于 IOptions 的 InMemoryDatabase 配置 DbContext

Configuring DbContext for InMemoryDatabase that also depends on IOptions

我想为单元测试创​​建 InMemoryDatabase。

我的 DbContext 派生自 ApiAuthorizationDbContext<ApplicationUser>,我无法在测试代码中实例化我的 DbContext,因为构造函数中缺少 operationalStoreOptions

我应该如何为我的上下文创建 operationalStoreOptions

DbContext

public class ApplicationDbContext : ApiAuthorizationDbContext<ApplicationUser>
{
   
    public ApplicationDbContext(
                DbContextOptions options,
                IOptions<OperationalStoreOptions> operationalStoreOptions) : base(options, operationalStoreOptions) { }

    public virtual DbSet<Assignment> Assignment { get; set; }
    public virtual DbSet<Course> Course { get; set; } 
                           ...........
    // More DbSet and OnModelCreating method
 }

我的测试代码

 var options = new DbContextOptionsBuilder<ApplicationDbContext>()
           .UseInMemoryDatabase(databaseName: "TestDbContext")
           .Options;
    

 //ApplicationDbContext needs 2 constructor parameter
 using (var _context = new ApplicationDbContext(options))
 {
   _context.Assignment.Add(new Assignment(1, "Test"));
   _context.SaveChanges();
 }

What should I do to create operationalStoreOptions for my context?

创建所需类型的实例,根据测试用例的需要进行填充,然后使用 Options.Create<TOptions> 获取所需的 IOptions 以注入上下文构造函数

var options = new DbContextOptionsBuilder<ApplicationDbContext>()
    .UseInMemoryDatabase(databaseName: "TestDbContext")
    .Options;

OperationalStoreOptions storeOptions = new OperationalStoreOptions {
    //populate needed members
};

IOptions<OperationalStoreOptions> operationalStoreOptions = Options.Create(storeOptions);

//ApplicationDbContext needs 2 constructor parameter
using (var _context = new ApplicationDbContext(options, operationalStoreOptions)) {
    _context.Assignment.Add(new Assignment(1, "Test"));
    _context.SaveChanges();
}

//...