Perfect!
As a wrap-up, I was trying to find a way to retrieve the last record in a database without knowing the record id and without knowing how many records are in the table. Various methods I employed were taking several seconds to execute which significantly slowed my application especially since the code was executed several times. The beginning and ending code is shown below with the change in execution times also shown. Note the execution times are only for my machine, but the relative change is significant nonetheless.
This is the code I started with:
_ Uses a GetMulti(Nothing) to retreive all records of an entity in a collection and then retrieves the record id of the Collection.Count - 1 Item. It slows down the more records you add to the database and has an initial overhead of several seconds even with only a few records._
Private Function GetLastSessionNum() As Integer
'get collection and return first item (should never be more than one)
Dim lastSession As Integer
Dim mySessions As New CollectionClasses.SynchSessionCollection
mySessions.GetMulti(Nothing)
If mySessions.Count > 0 Then
lastSession = mySessions.Item(mySessions.Count - 1).LastSynchSessionNum
Else
lastSession = 0
End If
'return the calc last session
Return lastSession
End Function
** This slow code to 3.5 seconds to execute.**
And this is the code I ended up with:
_ This code retrieves the maximum ** RecordID** in the table as an integer which is then used to retrieve an entity record and return the value we needed to begin with. The only requirement is that the table have a unique, consecutive identity (recordId), or another unique and ascending field. We use the Max Aggregate function to retrieve the record we need._
Private Function GetLastSessionNumAggregate() As Integer
'create sessions collection to hold results
Dim mySessions As New CollectionClasses.SynchSessionCollection
'create the max id number for the last record.
Dim mySessionIDMax As Integer = CType(mySessions.GetScalar(SynchSessionFieldIndex.LastSynchSessionId, Nothing, AggregateFunction.Max, Nothing), Integer)
Dim mySessionEntity As New EntityClasses.SynchSessionEntity(mySessionIDMax)
'return the result
If Not mySessionEntity.LastSynchSessionId < 0 Then
Return mySessionEntity.LastSynchSessionNum
Else
Dim mycol As New CollectionClasses.SynchSessionCollection
mycol.GetMulti(Nothing)
If mycol.Count > 0 Then
Throw New DataException("The maximum aggregate function failed in the ShareBuilder database as no max RecordID was retreived.")
Else
Return 0
End If
End If
End Function
** This improved code took 1.3 seconds to execute.**
If anyone has further suggestions to improve the code, I'd be grateful. For example, I assume there is a way to not only retrieve the max record ID, but also load that record at the same time.
Thanks for the quick answers.
David.