实体框架中推荐的身份生成方法是什么?
我对 StoreGeneratePattern 的最高效的方式感兴趣。
过去我习惯让数据库为我生成ID,但我想知道设置是否有任何优势,
StoreGeneratedPattern = None
而
StoreGeneratedPattern = Identity
不是我什至不确定当我将其设置为计算时会发生什么。
有什么建议吗?有没有与此相关的好文章,因为 msdn 解释得不是很清楚。我在架构中主要使用整数,而 GUID 很少。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
检查我的 关于
StoreGeneratePattern
的博客文章。它解释了身份
和计算
之间的一些差异。使用StoreGeneratePattern
作为 ID (PK) 时,如果您在应用程序中分配 ID,则正确的选项为None
;如果您在 DB 中分配 ID,则正确的选项为Identity
。Compated
选项是“无效”的,因为在每个实体持久化期间(也在更新中)值发生更改时使用此选项,而 ID 则不然。Identity
和Compulated
之间的区别在于执行的 SQL 命令的行为。如果属性是Identity
EF 将选择插入后的值并将其返回给您的应用程序。如果属性是Compulated
,EF 将选择插入和更新后的值并将其返回到您的应用程序。编辑:
StoreGeneratePattern.Identity
与数据库中的身份无关。您不需要在数据库中拥有 Identity,并且可以使用一些不同的技术设置 ID(guid 或触发器的默认值),但您仍然需要 StoreGeneratePattern.Identity 来将值返回给您的应用程序。一旦您使用
Identity
或Compulated
EF 将始终跟随每个 Insert 或 Update with Select 数据库生成的列。没有它它就无法工作。这些命令在数据库的单次往返中执行,因此几乎没有性能影响。Check my blog post about
StoreGeneratedPattern
. It explains some differences betweenIdentity
andComputed
. When usingStoreGeneratedPattern
for ID (PK) the correct option isNone
if you assign ID in the application orIdentity
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
andComputed
is behavior of executed SQL command. If property isIdentity
EF will select the value after Insert and return it to your application. If property isComputed
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 needStoreGeneratedPattern.Identity
to get value back to your application.Once you are using
Identity
orComputed
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.