ashilon
ashilon

Reputation: 1941

How to add a new entity marked with [DatabaseGenerated(DatabaseGeneratedOption.None)]

We have an entity, Role, marked with the attribute [DatabaseGenerated(DatabaseGeneratedOption.None)]. So far we have used seeding to seed the entities into the database. But now we want to create a new page to let users add/update roles. What is the right way to add new such entities to the database? Does Entity Framework does it automatically? Or do I first need to get the max id (a simple int column) and set it on the new entity? If so, is it safe, in terms of concurrency? Is there a right way to be concurrecy safe?

Upvotes: 2

Views: 535

Answers (2)

Stefan
Stefan

Reputation: 17658

Is there a right way to be concurrency safe?

Since you explicitly state

[DatabaseGenerated(DatabaseGeneratedOption.None)]

You disable the concurrency safe database-auto-generated Id's (primary keys/identity).

So your options are:

  • enable database generated id's
  • use natural keys
  • spend a lot of time creating a system that behaves like the database-auto-generated id's.
  • Another thing you could do is just change the PK to a uniqueidentifier instead, but if you have FKs off this, then that wouldn't work very well. Then you could just create a new guid for an insert and not worry about it. (@Daniel Lorenz's suggestion, see comment)

The entity framework is not really of much help here. Maybe you can elaborate why the database generated id's are disabled.

Upvotes: 1

aboersch
aboersch

Reputation: 128

If you seed the data using the SqlBulkCopy class, you can use the database-auto-generated ids, allowing you to use the best of both worlds (this is also more efficient if you are seeding a lot of data).

Upvotes: 2

Related Questions