Bru*_*lar 5 c# sqlite entity-framework-core
我有一个加载我的实体 ( 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;
}
Run Code Online (Sandbox Code Playgroud)
为了测试这种方法,我决定使用 SQLLite InMemory,因为我可以测试 Eager 加载功能。
上下文的设置:
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();
Run Code Online (Sandbox Code Playgroud)
但看起来 SQLite 总是加载其相关数据,这是有道理的,因为它已经在内存中。但是既然是模拟关系型数据库,有没有办法让它不自动加载相关数据呢?
如果没有,我怎样才能有效地测试它?我应该在磁盘 SQLite 中进行存储库测试吗?
(我在内存提供程序中使用 EF 来测试依赖于 的代码Repository)
您是否针对上下文的同一实例和DbSet刚刚插入的同一集合进行测试?如果是的话,这些对象就在那里,因为您刚刚在前面一步插入了它们,仍然在图表中。
尝试查询您的上下文,例如:
var c1 = context.Set<City>().AsQueryable().FirstOrDefault();
// assuming you have initialized the PointsOfInterest coll. in City.cs
Assert.Empty(c1.PointsOfInterest);
Run Code Online (Sandbox Code Playgroud)
_context.Set<City>().AsQueryable()您现在可以应用与存储库中相同的访问权限。
| 归档时间: |
|
| 查看次数: |
343 次 |
| 最近记录: |