C# Query 可以在上下文中独立更改
Posted
技术标签:
【中文标题】C# Query 可以在上下文中独立更改【英文标题】:C# Query can change independently in context 【发布时间】:2013-11-05 17:17:53 【问题描述】:我有一个难题。我已经看到查询中的记录数可以更改而无需重新运行相同的查询。 下面的代码展示了这个场景:
using (var db = new MyContext())
var query = from e in db.Entities select e;
//here the query.Count is equals to 100 for example
Thread.Sleep(10000);
//after some times the db has been populated
//here the query.Count is equals to 200 for example without run again the query
我的问题是:为什么会有这种行为?为什么它似乎是查询结果和数据层之间的自动绑定?实体框架在后台工作以更新查询结果? 提前致谢。
【问题讨论】:
我不确定我是否完全理解你的问题,但我相信答案是lazy loading 【参考方案1】:请记住,使用 IQueryable,感谢deferred execution,每次枚举查询时,即运行.Count()
、.ToList()
等时,查询都会针对数据库进行评估和执行。
如有疑问,请使用分析器(例如 MiniProfiler 或 EF Profiler)来准确了解您何时访问数据库。
【讨论】:
以上是关于C# Query 可以在上下文中独立更改的主要内容,如果未能解决你的问题,请参考以下文章
有没有办法使用 Wpf (C#) 更改 Web 浏览器的上下文菜单