FetchEntity and Predicates

Posts   
 
    
Fishy avatar
Fishy
User
Posts: 392
Joined: 15-Apr-2004
# Posted on: 31-Mar-2009 17:35:44   

I'm trying to use FetchEntity with Predicates and notice that that option does not exist. So, I wrote this code to accomplish it.

        Public Shared Function FetchEntity(ByVal predicate As RelationPredicateBucket, ByVal includeFields As List(Of EntityField2), Optional ByVal prefetch As List(Of PrefetchList) = Nothing) As ElemSchlHistEntity

            Using adapter As New CustomDataAccessAdapter

                Dim Entity As New ElemSchlHistEntity

                If predicate IsNot Nothing Then
                    Dim EntityCollection = FetchEntityCollection(predicate, includeFields, 1, Nothing, prefetch)
                    If EntityCollection IsNot Nothing AndAlso EntityCollection.Count = 1 Then
                        Return EntityCollection(0)
                    Else
                        Return Nothing
                    End If
                ElseIf adapter.FetchEntity(Entity, CreatePrefetchPaths(prefetch), Nothing, If(includeFields IsNot Nothing, New IncludeFieldsList(includeFields), Nothing)) Then
                    Return Entity
                Else
                    Return Nothing
                End If

            End Using

        End Function

        Public Shared Function FetchEntityCollection(Optional ByVal predicate As RelationPredicateBucket = Nothing, Optional ByVal includeFields As List(Of EntityField2) = Nothing, Optional ByVal maxRecords As Integer = 0, Optional ByVal sort As SortExpression = Nothing, Optional ByVal prefetch As List(Of PrefetchList) = Nothing) As EntityCollection(Of ElemSchlHistEntity)
            Using adapter As New CustomDataAccessAdapter

                Dim EntityCollection As New EntityCollection(Of ElemSchlHistEntity)
                adapter.FetchEntityCollection(EntityCollection, predicate, maxRecords, sort, CreatePrefetchPaths(prefetch), If(includeFields IsNot Nothing, New IncludeFieldsList(includeFields), Nothing))

                Return EntityCollection
            End Using
        End Function


Note: FetchEntityCollection just wraps llbl's FetchEntityCollection.

Is this an ok way of doing it or am I missing something?

Thanks,

Fishy

MTrinder
User
Posts: 1461
Joined: 08-Oct-2008
# Posted on: 31-Mar-2009 21:33:29   

Correct - there is no way to natively fetch a single entity with a normal predicate as you cannot guarantee that only one entity will be returned. You can define a unique constraint on a column in your db and LLBLGen will generate a method to fetch a single entity using that constraint.

http://www.llblgen.com/documentation/2.6/Using%20the%20generated%20code/Adapter/gencode_usingentityclasses_adapter.htm#Usingucvalue

Matt

Fishy avatar
Fishy
User
Posts: 392
Joined: 15-Apr-2004
# Posted on: 31-Mar-2009 22:12:11   

Thank you. simple_smile