Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OrmLite Update() vs Save()

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.

like image 869
Dru Avatar asked Feb 14 '23 05:02

Dru


1 Answers

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.

like image 200
reptildarat Avatar answered Feb 17 '23 13:02

reptildarat