2

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?

ashilon
  • 1,791
  • 3
  • 24
  • 41

2 Answers2

2

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

aboersch
  • 128
  • 10
1

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.

Stefan
  • 17,448
  • 11
  • 60
  • 79
  • We needed to have some tables (like the Roles table from my post) populated with values matching values from other, legacy tables. Now we need to be able to add new rows to some of them. BTW, the tables still have a primary key, named ID, it's just not an Identity column. – ashilon Mar 27 '17 at 12:24
  • You might want to check this post, I think the best you can try is to temporarily disable Id generation, insert your rows an re-enable it. I am not sure how to reset the seed (identity number) from that point but I think it will be the easiest option. Recreating the auto-database-identity insert can be a pain in large complex projects. If it's small you can lock it, get and insert the highest +1. It will work. http://stackoverflow.com/questions/13086006/how-can-i-force-entity-framework-to-insert-identity-columns – Stefan Mar 27 '17 at 12:30
  • 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 Mar 28 '17 at 17:42
  • @stefan While this approach works it prevents you from using entity framework code first or migrations. – aboersch Mar 29 '17 at 07:34