gpt4 book ai didi

entity-framework - 如何处置 Entity Framework Core 内存数据库

转载 作者:行者123 更新时间:2023-12-04 08:28:55 25 4
gpt4 key购买 nike

我想在每个单元测试中创建干净的内存数据库。
当我运行多个测试时,来自先前测试的数据保留在数据库中。如何处置现有的内存数据库?

我使用以下代码初始化每个测试:

 [TestInitialize]
public void TestInitialize()
{
Services = new ServiceCollection();
Services.AddScoped<DbContextOptions<MyDbContext>>(sp => new DbContextOptionsBuilder<TacsDbContext>()
.UseInMemoryDatabase("MyTestDbContext")
.Options);

Services.AddTransient<InMemoryMyDbContext>();
Services.AddTransient<MyDbContext>(sp => sp.GetService<InMemoryTacsDbContext>());

ServiceProvider = Services.BuildServiceProvider();
}

[TestMethod]
public void Test1()
{
using (var dbContext = ServiceProvider.GetService<MyDbContext>()) ...
}

[TestMethod]
public void Test2()
{
using (var dbContext = ServiceProvider.GetService<MyDbContext>()) ...
}

我使用 .NET Core 2.0 和 Entity Framework Core 2.0

编辑
我无法使用标准注册: Services.AddDbContext<InMemoryMyDbContext>(...) , 因为
public class InMemoryMyDbContext : MyDbContext
{
public InMemoryMyDbContext(DbContextOptions<InMemoryMyDbContext> options)
: base(options) { } //compiler error

public InMemoryMyDbContext(DbContextOptions<MyDbContext> options)
: base(options) { } //runtime IoC error
}

public class MyDbContext : DbContext
{
public MyDbContext(DbContextOptions<MyDbContext> options)
: base(options) { }
}

最佳答案

考虑使用 Nuget 包 努力
它是一个简单快速的内存数据库,非常适合单元测试
你可以用一个空的数据库启动它;如果需要,使用数据库播种器填充它,或者使用测试 CSV 文件中的值填充它。
Tutorials Effort - Entity Framework Unit Testing Tool
您的 DbContext 可能类似于:

class MyDbContext : DbContext
{
public MyDbContext() : base() { } // constructor using config file
public BloggingContext(string nameOrConnectionString) :
base(nameOrConnectionString) { }

public DbSet<...> ...{ get; set; }
public DbSet<...> ...{ get; set; }
}
只需添加一个构造函数,您就可以像使用原始数据库一样使用内存数据库:
 public MyDbContext(DbConnection connection) : base(connection, true) { }
您将 DbConnection 传递给测试数据库,此连接传递给 DbContext 类。 true 参数表示当 DbContext 被释放时,DbConnection 也应该被释放。
用法是:
[TestMethod]
public void UnitTest_X()
{
var dbConnection = Effort.DbConnectionFactory.CreateTransient();
using (var dbContext = new MyDbContext(dbConnection)
{
// perform your test of MyDbContext as if it was connected to your
// original database
}
}
可以在 here on StackOverFlow 中找到带有使用一对多关系的 Effort 数据库的控制台程序的简单复制粘贴代码示例。

关于entity-framework - 如何处置 Entity Framework Core 内存数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46850890/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com