Dapper.FSharp icon indicating copy to clipboard operation
Dapper.FSharp copied to clipboard

Working with auto increment IDs

Open Slesa opened this issue 2 years ago • 3 comments

Consider an order with an auto ID field, which can have multiple orderlines.

type Order = { Id: int64 option }
type OrderLine = { Id: int64 option; order: int64 }

Is there an example how to get the value of this generated ID in order to use it as the reference in the orderlines? I know this can be done manually with

INSERT INTO Order(...) values(...) SELECT SCOPE_IDENTITY()

or "; SELECT last_insert_rowid()" for MSSql/Postgres

but maybe there is a more comfortable way?

And probably there is no other way than keep the ID as option, isn't it?

Slesa avatar Feb 01 '23 10:02 Slesa

Your primary key fields should not be optional. I don’t think any database even allow setting a nullable field as the PK.

Use InsertOutputAsync to return the generated id field value.

JordanMarr avatar Feb 01 '23 18:02 JordanMarr

I see this part is missing in the documentation so if you would @Slesa send a PR with some description for *OutputAsync methods, it may help others for next time.

Dzoukr avatar Feb 02 '23 07:02 Dzoukr

Well I would like to, but... maybe it is because of monday, or I am too slow in thinking in general :) When I use Order with Id set, I get the error 'Can not set explicit value on identity'. When I use an OrderDto w/o Id field, I cannot persist as it is a table of Orders, not OrderDtos. And I could not access the Id field anyway...

PS: @JordanMarr is right, the Id field cannot be optional

I bet it has sth to do with the Persons.View.generate in the tests somehow...

Slesa avatar Feb 06 '23 09:02 Slesa