通过 ObjectContext 基础实例进行 EF4 预加载
使用 ORM 时,我通常创建一个工厂方法来返回 DataContext / ObjectContext 实例,然后用它来查询数据源。我通常让我的工厂返回基本上下文类;因此,对于 EF4,我返回一个 ObjectContext 类型实例,而不是生成的“MyDBConext”实例。方法签名如下所示:
ObjectContext CreateContext()
此 CreateContext 方法返回一个带有 LazyLoadingEnabled = false 和 ProxyCreationEnabled = false 选项的实例。当访问实体集合时,我会调用类似 ctx.CreateObjectSet() 的方法,其中 T 当然是实体类型。
我注意到,当我使用 ObjectContext 类型实例而不是“MyDBConext”时,急切加载似乎不起作用。
User result = null;
using(ObjectContext ctx = ContextFactory.CreateContext()) {
ObjectSet<User> userSet = ctx.CreateObjectSet<User>();
//userSet.Include(x => x.Roles);
userSet.Include("Roles");
result = userSet.SingleOrDefault(exp);
}
return result;
但是将 using 语句更改为类似的内容
using(MyDBConext ctx = new MyDBConext()) {
可以按预期工作。但为什么?我可以不通过基本 ObjectContext 实例预先加载吗?
When using ORMs I usual create a factory method to return the DataContext / ObjectContext instance that I'll then use to query the data source. I usually have my factories return the base context class; so in the case of EF4 I return an ObjectContext type instance as opposed to the generated "MyDBConext" instance. The method signature looks something like this:
ObjectContext CreateContext()
This CreateContext method returns an instance with LazyLoadingEnabled = false and ProxyCreationEnabled = false options. When accessing the entity collections I'd call something like ctx.CreateObjectSet() where T of course is the entity type.
I've noticed that when I use the ObjectContext type instance as opposed to a "MyDBConext", eager loading does not seem to work.
User result = null;
using(ObjectContext ctx = ContextFactory.CreateContext()) {
ObjectSet<User> userSet = ctx.CreateObjectSet<User>();
//userSet.Include(x => x.Roles);
userSet.Include("Roles");
result = userSet.SingleOrDefault(exp);
}
return result;
But changing the using statement to something like
using(MyDBConext ctx = new MyDBConext()) {
works as expected. But why? Can I not eager load via the base ObjectContext instance?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
以下是我解决问题的方法,
我认为 include 语句更改了 ObjectSet / ObjectQuery 的当前实例并将其返回。我认为这就是大多数 Fluent api 的设计工作方式。将 Include 内联放置并链接方法调用会产生预期的查询结果。这是关于 EF 的 Fluent api 的一个有趣的“事实”
Here's how I solved my issue
I thought that the include statement altered the current instance of the ObjectSet / ObjectQuery and returned it it. I thought thats how most fluent api's were designed to work. Placing the Include inline and chaining the method calls produced the query results as expected. This is an interesting "fact" about the fluent api of EF