Question

I am trying to save a new object to the database using petapoco. I have an object that uses a Guid for the primary key.

Here is an example of the objects primary key property.

<PetaPoco.Column()> _
Public ReadOnly Property Primkey() As Guid Implements IStandardDocument.Primkey
    Get
        Return (_primkey)
    End Get
End Property

Here is an example of the save method.

database.Save("Reservations", "Primkey", reservation)

The sql that is generated is an update with a primkey of 00000000-0000-0000-0000-000000000000 instead of an insert. So new records are never inserted.

If I have an existing object with a valid guid the update and delete all work correctly.

What am I doing wrong for the save case?

Was it helpful?

Solution 2

I was able to make this work by removing the type from the primkey property. Setting the primkey to null will now return null rather than an empty guid.

PetaPoco now sees the primarykey field is a null and generate the correct insert statement rather than generating an update statement for primkey 00000000-0000-0000-0000-000000000000.

OTHER TIPS

Most likely it's too late to answer this for the original poster, but for others out there... My understanding is the Save doesn't work for Guid columns. The way petaPoco knows if it's an insert vs update is if the key value is different from default. In case if numeric it would be 0, in the case of Guid it would be '00000000-0000-0000-0000-000000000000'. Here's an extract of IsNew method

// Common primary key types
            if (type == typeof(long))
                return (long)pk == 0;
            else if (type == typeof(ulong))
                return (ulong)pk == 0;
            else if (type == typeof(int))
                return (int)pk == 0;
            else if (type == typeof(uint))
                return (uint)pk == 0;
// Create a default instance and compare
return pk == Activator.CreateInstance(pk.GetType());

In the case of Guid the last statement would always return false, even if your primary key is all zeros. There should really be another else if as such:

else if (type == typeof(Guid))
                return Guid.Equals(pk, Activator.CreateInstance(pk.GetType()));

However, I didn't check if this is the only thing that has to be changed for the GUID key to work. After inserting the record, PetaPoco tries to check the key value of the newly inserted record and it might fail on that too.

I've never worked with petapoco but a few things I would try first are:-

  1. Primkey column's Data Type in sql is 'Uniqueidentifier'
  2. Primkey column's Default Value is (newid())
  3. Change the PrimKey to a Get/Set value and do 'Primkey = Guid.NewGuid' before saving.

EDIT: I just thought, when you declare a New Reservation does it allow you to pass an ID ect on the constructor?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top