【问题标题】:Entity Framework Core SQLite - Simulate Eager Loading in testEntity Framework Core SQLite - 在测试中模拟 Eager Loading
【发布时间】: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


【解决方案1】:

您是否正在针对您的上下文的同一实例和您刚刚插入的同一 DbSet 集合进行测试?如果是,那么这些对象就在那里,因为您刚刚在前一步插入了它们,仍然在图表中。

尝试查询您的上下文,例如:

var c1 = context.Set<City>().AsQueryable().FirstOrDefault();
// assuming you have initialized the PointsOfInterest coll. in City.cs
Assert.Empty(c1.PointsOfInterest); 

您现在可以在您的存储库中应用与_context.Set&lt;City&gt;().AsQueryable() 相同的访问权限。

【讨论】:

    猜你喜欢
    • 2016-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多