帮助我了解实体框架4缓存的延迟加载 [英] Help me understand entity framework 4 caching for lazy loading

查看:149
本文介绍了帮助我了解实体框架4缓存的延迟加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在实体框架4.0中获得了一些意想不到的行为,我希望有人可以帮助我理解这一点。为了这个问题的目的,我正在使用northwind数据库。我也使用默认代码生成器(不是poco或自我跟踪)。我期望随时查询框架的上下文,只有当我还没有获取这些对象时,才能进行往返。如果我关闭延迟加载,我会得到这个行为。目前在我的应用程序中,我正在轻松地打开延迟加载,然后将其关闭,以便我可以获得所需的行为。那真的很烂,所以请帮忙。这是一个很好的代码示例,可以演示我的问题。

I am getting some unexpected behaviour with entity framework 4.0 and I am hoping someone can help me understand this. I am using the northwind database for the purposes of this question. I am also using the default code generator (not poco or self tracking). I am expecting that anytime I query the context for the framework to only make a round trip if I have not already fetched those objects. I do get this behaviour if I turn off lazy loading. Currently in my application I am breifly turning on lazy loading and then turning it back off so I can get the desired behaviour. That pretty much sucks, so please help. Here is a good code example that can demonstrate my problem.

Public Sub ManyRoundTrips()
    context.ContextOptions.LazyLoadingEnabled = True
    Dim employees As List(Of Employee) = context.Employees.Execute(System.Data.Objects.MergeOption.AppendOnly).ToList()

    'makes unnessesary round trip to the database, I just loaded the employees'
    MessageBox.Show(context.Employees.Where(Function(x) x.EmployeeID < 10).ToList().Count)
    context.Orders.Execute(System.Data.Objects.MergeOption.AppendOnly)
    For Each emp As Employee In employees
        'makes unnessesary trip to database every time despite orders being pre loaded.'
        Dim i As Integer = emp.Orders.Count
    Next
End Sub

Public Sub OneRoundTrip()
    context.ContextOptions.LazyLoadingEnabled = True
    Dim employees As List(Of Employee) = context.Employees.Include("Orders").Execute(System.Data.Objects.MergeOption.AppendOnly).ToList()

    MessageBox.Show(employees.Where(Function(x) x.EmployeeID < 10).ToList().Count)

    For Each emp As Employee In employees
        Dim i As Integer = emp.Orders.Count
    Next
End Sub

为什么第一个代码块进行不安全的回程?

Why is the first block of code making unnessesary round trips?

推荐答案

你的期望是不正确的。查询始终查询数据库。总是。这是因为LINQ总是转换为SQL。

Your expectation is not correct. Queries always query the DB. Always. That's because LINQ is always converted to SQL.

要从上下文中加载一个对象,如果它已经被提取,并且如果没有从数据库中加载对象,请使用 ObjectContext.GetObjectByKey()

To load an object from the context if it's already been fetched and from the DB if it hasn't, use ObjectContext.GetObjectByKey().

这篇关于帮助我了解实体框架4缓存的延迟加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆