When using OrmLite to add an entry into the database there seems to be two ways of doing it:
dbConn.Insert(customer);
and
dbConn.Save(customer);
When using Insert() the AutoIncrement ID field does not get updated, but when using Save() it does.
If you use:
dbConn.LastInsertId();
It will return the correct ID if Save() is used but the wrong ID if Insert() is used.
Why do these two methods exist? Using Insert() will add an entry to the database with the correct ID, it is just not reflected in the POCO model. It seems strange that there are no exceptions thrown and no indication of a problem, when you can end up using the wrong ID and get hard to track bugs if you are not aware of this.
It's already mentioned in the documentations:
Save and SaveAll will Insert if no record with Id exists, otherwise it Updates. Both take multiple items, optimized to perform a single read to check for existing records and are executed within a sinlge transaction.
For Insert operation, it's pretty straighforward, there's nothing special in that functions.
So, Use Insert when you know there's no duplicated key in your records, otherwise use save method.
If you want to retrieve the LastInsertId, with Insert method, you need to specify the [AutoIncrement] on your POCO.
UPDATE: When you set your IDbConnectionFactory using Singelton With Lazy< T > implementation, it seems the LastInsertId will not working. so just use lock or static implementation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With