c# - 在 Entity Framework 中使用 DbSet<TEntity>.Local 属性

标签 c# entity-framework caching local dbset

正在关注 MSDN documentation我们可以使用 Local 属性直接从上下文中获取本地/缓存数据,而无需对数据源进行额外请求:

Gets an ObservableCollection that represents a local view of all Added, Unchanged, and Modified entities in this set.
(...)
This property can be used for data binding by populating the set with data, for example by using the Load extension method, and then binding to the local data through this property.

问题是,代码不工作(Local 是空的):

context.SampleEntities.Select(x => new { x.A, x.B }).Load();
// context.SampleEntities.Local.Count is 0

但在这种情况下,它似乎工作正常:

context.SampleEntities.Load();
// context.SampleEntities.Local.Count is not 0

也许有人可以解释一下使用Local 属性的正确方法是什么?
更重要的是,如何将它用于部分加载的实体,如上例所示?

最佳答案

这是预期的行为。本地缓存在 DbContext 对象的生命周期内由您从数据库加载的实体。带查询:

context.SampleEntities.Select(x => new { x.A, x.B })

您没有向应用程序内存加载 SampleEntity 对象,而只有它的属性 A 和 B。Select 也被转换为 sql 查询以限制从查询返回的行,从而提高性能。

关于c# - 在 Entity Framework 中使用 DbSet<TEntity>.Local 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29716884/

相关文章:

c# - 由任务计划程序启动时隐藏 C# 控制台应用程序窗口

c# - 是否可以将非主键设置为另一个表中的外键?

html - 强制Grails不缓存 “cache manifest”文件?

ruby-on-rails - 如何在 Node.js 中解码/解压缩 memcached 支持的 Rails 缓存(Dalli gem)中的值

android - 更新用户的个人资料图片

c# - 您如何确定 Internet 连接是否可用于您的 WinForms 应用程序?

c# - 为两个 OpenGL 上下文调用 wglsharelists 时诊断错误 1008

c# - 如何在运行时读取给定项目中的 MSBuild 属性?

c# - 动态创建 GroupBy 并使用 EF 选择

c# - Entity Framework 错误 "Entity type is not mapped."