Dzoukr / Dapper.FSharp

Lightweight F# extension for StackOverflow Dapper with support for MSSQL, MySQL, PostgreSQL, and SQLite
MIT License
365 stars 35 forks source link

Working with auto increment IDs #80

Open Slesa opened 1 year ago

Slesa commented 1 year ago

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?

JordanMarr commented 1 year ago

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.

Dzoukr commented 1 year ago

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.

Slesa commented 1 year ago

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...