What is the recommended identity generation approach in Entity framework?
Asked Answered
D

1

10

I am interested in what is the most performant way for StoreGeneratedPattern.

In past I was used to let the DB generate the ID for me but I was wondering if there is any advantage in setting

StoreGeneratedPattern = None 

instead of

StoreGeneratedPattern = Identity

I am not even sure what happens when I set it to Calculated.

Any recommendations? Is there any nice article related to this because msdn is not very explanatory. I am using mostly ints with few GUIDs in my schema.

Decrement answered 17/3, 2011 at 0:28 Comment(0)
G
20

Check my blog post about StoreGeneratedPattern. It explains some differences between Identity and Computed. When using StoreGeneratedPattern for ID (PK) the correct option is None if you assign ID in the application or Identity if you assign ID in DB. Computed option is "invalid" because this option is used when value is changed during each entity persistence (also in updates) and it is not the case of ID.

The difference between Identity and Computed is behavior of executed SQL command. If property is Identity EF will select the value after Insert and return it to your application. If property is Computed EF will select the value after both Insert and Update and return it to your application.

Edit:

StoreGeneratedPattern.Identity is not related to Identity in DB. You don't need to have Identity in DB and you can set ID with some different techinque (default value for guid or trigger) but you still need StoreGeneratedPattern.Identity to get value back to your application.

Once you are using Identity or Computed EF will always follow each Insert or Update with Select for db generated columns. It can't work without it. These commands are executed in single roundtrip to database so there is almost none performance impact.

Gunn answered 17/3, 2011 at 8:33 Comment(1)
thanks, this mostly answers my question. There is still ONE more dilemma. I can set id column in db to not be identity but still be a primary key. In this case EF will generate new id for me. How does it do? Two sql queries? Is it efficient? I haven't got profiler. thanksDecrement

© 2022 - 2024 — McMap. All rights reserved.