Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework SET IDENTITY_INSERT

Is there a way to force the ID value for a new entity in EF when we have an auto-incrementing ID column, i.e. use SET IDENTITY_INSERT behaviour through EF?

Our requirement is that our create form must always show a new, unique ID for the object we're creating on the empty form before it is filled in or saved. The idea is that this ID can be out read to someone over the phone and then the user can complete and save the form after the call is complete. We could reserve an ID by inserting an empty row into the database there and then, but we have unique columns and FKs; instead I've made a 'next ID' table that we increment with locks for safety, and I test this against the top ID in the object table too to be careful. The idea was to then force the use of this new ID when we write back the entity - but I can't see how to get EF to do it.

Is that possible - is it just something I've missed? I don't think the ID even makes it down to the insert so I don't think manually calling SET IDENTITY_INSERT around the SaveChanges would help.

Or do I have to do something else? I can see alternatives:

  • Change our ID column to not be an identity and take manual control of it all: there's a table ID inheritance here so this is potentially tricky too.
  • Separate DB ID and user-visible ID into a separate column, and record our unique ID there.
  • Empty row to reserve the ID, as above; might need some nullability changes, and amending our data read code to ignore these records.

Thanks! This is EF4 (using an EDMX and generated classes not POCOs), and against SQL Server 2008 in case that matters.

like image 693
Rup Avatar asked Nov 15 '22 03:11

Rup


1 Answers

Why not use a Guid as primary key. Nothing to do with auto-increment, no concurrency pitfalls etc. You just create the Guid at the moment you create the form. Hand it over to a caller and fill in the form afterwards. When the form is cancelled, no problem. When the form is finished create the entity with the created Guid set the other values of the entity object, apply it to the (a) context and SaveChanges()...

like image 89
Bernoulli IT Avatar answered Feb 19 '23 21:02

Bernoulli IT