ca9*_*3d9 10 c# entity-framework xunit entity-framework-core
我有以下代码在 .Net core 2.0 控制台程序中设置 DBContext,并将其注入到主应用程序类的构造函数中。
IConfigurationRoot configuration = GetConfiguration();
services.AddSingleton(configuration);
Conn = configuration.GetConnectionString("ConnStr1");
services.AddDbContext<MyDbContext>(o => o.UseSqlServer(Conn));
Run Code Online (Sandbox Code Playgroud)
现在我创建了一个 xUnit 测试类,需要初始化相同的 DbContext 进行测试。
context = new MyDbContext(new DbContextOptions<MyDbContext>());
Run Code Online (Sandbox Code Playgroud)
它得到参数connectionString不能为空的错误。如何在测试项目中正确设置 DbContext?
我找到了一种方法。
var dbOption = new DbContextOptionsBuilder<MyDbContext>()
.UseSqlServer("....")
.Options;
Run Code Online (Sandbox Code Playgroud)
小智 5
在乔治·亚历山大是为我工作的解决方案:
var optionsBuilder = new DbContextOptionsBuilder<MyDbContext>();
optionsBuilder.UseInMemoryDatabase();
var context = new MyDbContext(optionsBuilder.Options);
Run Code Online (Sandbox Code Playgroud)
该UseInMemoryDatabase扩展方法被包括在Microsoft.EntityFrameworkCore.InMemory
| 归档时间: |
|
| 查看次数: |
7656 次 |
| 最近记录: |