【发布时间】:2018-04-07 21:40:39
【问题描述】:
我有一个存储库,用于加载我的实体 (City) 及其相关数据 (PointsOfInterest)
public City GetCity(int cityId, bool includePointsOfInterest)
{
var city = _context.Cities.SingleOrDefault(x => x.Id == cityId);
if (includePointsOfInterest)
{
_context.Entry(city)
.Collection(x => x.PointsOfInterest)
.Load();
}
return city;
}
为了测试这个方法,我决定使用 SQLLite InMemory,因为我可以测试 Eager load 功能。
上下文设置:
SqliteConnection connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<CityInfoContext>()
.UseSqlite(connection)
.Options;
var context = new CityInfoContext(options);
var cities = new List<City>()
{
new City()
{
Id = 1,
Name = "New York City",
Description = "The one with that big park.",
PointsOfInterest = new List<PointOfInterest>()
{
new PointOfInterest()
{
Id = 1,
Name = "Central Park",
Description = "The most visited urban park in the United States."
},
new PointOfInterest()
{
Id = 2,
Name = "Empire State Building",
Description = "A 102-story skyscraper located in Midtown Manhattan."
}
}
}
}
context.Cities.AddRange(cities);
context.SaveChanges();
但看起来 SQLite 总是加载其相关数据,这是有道理的,因为它已经在内存中。但是既然要模拟关系型数据库,有没有办法让它不自动加载相关数据?
如果没有,我该如何有效地测试它?我应该在磁盘 SQLite 中进行存储库测试吗?
(我在内存提供程序中使用 EF 来测试依赖于 Repository 的代码)
【问题讨论】:
-
你能分享你测试的代码吗? EF 不急于加载。还有其他原因导致数据被加载。
-
我也遇到了同样的效果。我将尝试使用基于文件的数据库,而不是使用
Datasource=:memory: -
有人找到解决方案了吗?遗憾的是,它降低了测试的可靠性。
-
@Tjaart 在我们的项目中,我们使用包装在事务中的本地 SQL。这是当时找到的最佳解决方案。
标签: c# sqlite entity-framework-core