实体框架核心SQLite - 在测试中模拟Eager Loading

时间:2017-10-26 13:19:02

标签: 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;
}

为了测试这个方法,我决定使用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();

但看起来SQLite总是加载其相关数据,这是有道理的,因为它已经在内存中。但由于它应该模拟关系数据库,有没有办法让它不自动加载相关数据?

如果没有,我该如何有效地测试它?我应该在磁盘SQLite中进行存储库测试吗?

(我在内存提供程序中使用EF来测试依赖于Repository)的代码

1 个答案:

答案 0 :(得分:0)

您是否针对上下文的相同实例和刚插入的DbSet集合进行了测试?如果你是,那么对象就在那里,因为你刚刚在图中插入了一步。

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

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

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