加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

vb.net – 延迟加载带有条件的实体框架EntityCollection

发布时间:2020-12-17 00:11:24 所属栏目:大数据 来源:网络整理
导读:在Entity Framework中(特别是EF 3.5,但如果它存在于EF 4中,它给我一个升级的理由)是否可以延迟加载只是集合的一部分?我也可能接近这个错误,所以我愿意接受建议.我的表/实体看起来类似于: Person PersonMeal Meal------ 1---* ---------- *---1 -----ID ID
在Entity Framework中(特别是EF 3.5,但如果它存在于EF 4中,它给我一个升级的理由)是否可以延迟加载只是集合的一部分?我也可能接近这个错误,所以我愿意接受建议.我的表/实体看起来类似于:
Person            PersonMeal           Meal
------    1---*   ----------   *---1   -----
ID                ID                   ID
...               PersonID             ...
                  MealID
                  Value
                  ...

我有一个通过存储过程通过Entity Framework检索的Person对象列表.我有一个观点,一次只显示一顿饭,所以我只想要与那顿饭相关的信息.目前我的代码如下所示:

Function GetPersons() As List(Of Person)
    Dim personList = context.StoredProcedureCall(param1,param2,param3).ToList()
    personList.ForEach(Function(x) LazyLoadProperties(x))
    Return personList
End Function

' Work around function because VB lambdas don't take Sub's
Function LazyLoadProperties(ByVal person As Person) As Object
    If (Not person.PersonMeal.IsLoaded) Then
        person.PersonMeal.Load()
    End If
    Return Nothing
End Function

问题是这会加载整个集合.虽然它是一个小集合,所以最糟糕的情况我可以加载它然后删除所有我需要的,但这远非理想.另外,我不确定是否可以在不触发修改集合的任何事件的情况下,因为它们本来不应该在那里.

在这种情况下,您可以只查询数据库中的数据,而不是使用Load方法:
Function GetPersons() As List(Of Person)
    Dim personList = context.StoredProcedureCall(param1,param3).ToList()

    Dim person As Person
    For Each person in personList
        person.PersonMeals = From pm in context.PersonMeals.Include("Meal")
                             Where pm.Person.Id == person.Id And pm.Meal.Id == Meal_ID
                             Take 1
    Next person

    Return personList
End Function

我假设person.PersonMeals是一个集合,否则你可以使用FirstOrDefault而不是Take.

在此查询中,我们基本上选择所有PersonMeals实体(连同Meal),其中人员ID作为循环中的当前人员和您想要的膳食ID.如果您的数据库没有损坏的数据(多行具有相同的PersonID-MealID组合),则会有0或1个结果,这些结果将写入您的PersonMeals属性.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读