问题
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.
回答1:
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.
来源:https://stackoverflow.com/questions/5333417/what-is-the-recommended-identity-generation-approach-in-entity-framework