Generating a Primary Key

Posts   
 
    
Steve Mann
User
Posts: 31
Joined: 22-Nov-2006
# Posted on: 06-Dec-2006 10:24:58   

I'm on 2.0.0.0 final, using SQL Server 2000, SelfServicing, Two classes, VB.NET in Visual Studio 2005.

Our old database has tables with PKs with more than one field, eg TypeID and SubTypeID, but also a unique TableID which is an 'Identity' field but not defined as such in SQL Server, so we have to select max(TableID) and add 1 to it within a transaction before an Insert.

rage (I didn't design this!)

What's the best way to do this using LLBLGEN?

Walaa avatar
Walaa
Support Team
Posts: 14995
Joined: 21-Aug-2005
# Posted on: 06-Dec-2006 15:06:08   

Before inserting a new row, Read the Max TableID from the database, using scalar query. Use the yourEntityCollection.GetScalar() method.

Steve Mann
User
Posts: 31
Joined: 22-Nov-2006
# Posted on: 06-Dec-2006 15:14:41   

Thank you.

I found that this worked:

Public Overrides Sub ValidateEntityBeforeSave(ByVal involvedEntity As IEntityCore)
            Dim toValidate As Abilty1Entity = CType(involvedEntity, Abilty1Entity)

            If toValidate.IsNew Then
                toValidate.CrtTs = Now
                Dim clnAny As New Abilty1Collection()
                Dim lngPK As Integer = CInt(clnAny.GetScalar(Abilty1FieldIndex.AbtyId, AggregateFunction.Max)) + 1
                toValidate.AbtyId = lngPK
            Endif 

            MyBase.ValidateEntityBeforeSave(involvedEntity)
End Sub

However, this could go wrong unless the table is locked (two users get PK 123, the first Inserts, the second crashes). Can I wrap this in a Transaction somehow (in the GUI if need be)?

Walaa avatar
Walaa
Support Team
Posts: 14995
Joined: 21-Aug-2005
# Posted on: 06-Dec-2006 15:18:23   

Yeah, that's the problem about this solution, and I think you would need to place the reading & updating of the TableID inside a critical section.

Otis avatar
Otis
LLBLGen Pro Team
Posts: 39927
Joined: 17-Aug-2003
# Posted on: 07-Dec-2006 10:43:20   

As MAX() based sequences are never reliable, you'll always run into problems because without locks on the complete table, there is always a risk of having duplicates.

Frans Bouma | Lead developer LLBLGen Pro