使用包含对象查询的Where子句实体(实体框架)

时间:2013-09-02 01:55:15

标签: wpf entity-framework linq-to-entities where-clause objectquery

我使用Entity Framework作为WPF数据库前端的基础。

我的数据库结构适用于办公楼,对于这个问题,您需要了解的是,顶级实体被称为市场(想想郊区或中央商务区)。市场有很多属性和属性有很多调查。

我想将调查仅限于最近的10次调查(调查每6个月进行一次)。

我可以看到自动生成的代码如何构建查询:

Dim OMRMarketsQuery As System.Data.Objects.ObjectQuery(Of OMR.OMRInterfaceCustomCode.OMRMarket) = OMRInterfaceEntities.OMRMarkets

    OMRMarketsQuery = OMRMarketsQuery.Include("Properties")

    OMRMarketsQuery = OMRMarketsQuery.Include("Properties.OMRBuildingSurveys")

我想使用where子句来过滤OMRBuildingSurvey实体的属性。我可以编写一个where子句来过滤市场ID(顶级实体),如下所示:

MRMarketsQuery = OMRMarketsQuery.Include("Properties.OMRBuildingSurveys").Where("it.ID >1000")

但我想过滤OMRBuildingSurveys实体的属性,我似乎无法找到导航到它的方法。我试过了:

OMRMarketsQuery = OMRMarketsQuery.Include("Properties.OMRBuildingSurveys").Where("it.Properties.OMRBuildingSurvey.ID >1000")

但我收到错误:

An unhandled exception of type 'System.Data.EntitySqlException' occurred in System.Data.Entity.dll

    Additional information: 'OMRBuildingSurvey' is not a member of 'Transient.collection[OMRInterfaceModel.Property(Nullable=True,DefaultValue=)]'. To extract a property of a collection element, use a subquery to iterate over the collection.

如果有人能指出我正确的方向,我真的很感激!

非常感谢,祝你有个美好的一天!

1 个答案:

答案 0 :(得分:-1)

好的答案很简单。

在使用“预先加载”或“延迟加载”时,您无法进行过滤。我自己和几个自由职业者尝试了各种方法,但答案是加载市场和属性,然后注释掉以下代码:

'OMRMarketsQuery = OMRMarketsQuery.Include("Properties.OMRBuildingSurveys")

要加载调查详细信息,我们捕获了属性选择器列表框已更改事件,这是我们可以按如下方式过滤的地方:

Private Sub Lbx_PropsByNameSelector_SelectionChanged(sender as Object,e As SelectionChangedEventArgs)处理Lbx_PropsByNameSelector.SelectionChanged

Dim propertyAdListBox = CType(sender, ListBox)
Dim selectedProperty = CType(propertyAdListBox.SelectedItem, OMRInterfaceCustomCode.Property)

If Not IsDBNull(selectedProperty) Then

    Dim RSurveysQuery = From r In OMRInterfaceEntities.OMRBuildingSurveys Where r.PeriodID > 80 And r.PropertyID = selectedProperty.ID

    Dim RSurveysList = RSurveysQuery.ToList

    If RSurveysList.Any() Then
        Dim RecentSurveysSource = CType(Me.FindResource("OMRMarketsPropertiesOMRBuildingSurveysViewSource"), CollectionViewSource)
        RecentSurveysSource.Source = RSurveysList
    End If
End If

End Sub