花了很多时间,但仍然无法理解如何避免在DbContext中进行缓存。
我在下面附上了一些简单案例的实体模型来演示我的意思。
问题在于 dbcontext 缓存结果。例如,我有下一个用于从数据库查询数据的代码:
using (TestContext ctx = new TestContext())
{
var res = (from b in ctx.Buildings.Where(x => x.ID == 1)
select new
{
b,
flats = from f in b.Flats
select new
{
f,
people = from p in f.People
where p.Archived == false
select p
}
}).AsEnumerable().Select(x => x.b).Single();
}
在这种情况下,一切都很好:我得到了我想要的(只有 Archived == false 的人)。
但是,如果我在其后添加另一个查询,例如,查询有人将“已存档”标志设置为 true 的建筑物,我会遇到接下来的事情,我真的无法理解:
- 我之前的结果是res,将通过数据添加(有
也将添加 Archived == true 的人员)
- 新结果将绝对包含所有 Person,无论 Archived 等于什么
该查询的代码如下:
using (TestContext ctx = new TestContext())
{
var res = (from b in ctx.Buildings.Where(x => x.ID == 1)
select new
{
b,
flats = from f in b.Flats
select new
{
f,
people = from p in f.People
where p.Archived == false
select p
}
}).AsEnumerable().Select(x => x.b).Single();
var newResult = (from b in ctx.Buildings.Where(x => x.ID == 1)
select new
{
b,
flats = from f in b.Flats
select new
{
f,
people = from p in f.People
where p.Archived == true
select p
}
}).AsEnumerable().Select(x => x.b).Single();
}
顺便说一下,我设置了启用延迟加载在 TestContext 的构造函数中设置为 false。
有人知道如何解决这个问题吗?我怎样才能在我的查询中得到我在 linq to 实体中真正写的内容?
附: @Ladislav 你可以帮忙吗?