What is the recommended identity generation approach in Entity framework?

安稳与你 提交于 2020-01-01 02:56:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!