实体框架中推荐的身份生成方式是什么? [英] What is the recommended identity generation approach in Entity framework?

查看:126
本文介绍了实体框架中推荐的身份生成方式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对StoreGeneratedPattern最有效的方式感兴趣。

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

过去我习惯让DB为我生成ID,但是我想知道在设置

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 

而不是

StoreGeneratedPattern = Identity

我不确定当我将其设置为Calculated时会发生什么。

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

任何建议?有没有什么好的文章与此相关,因为msdn不是很明白。我在我的架构中大部分使用几个GUID的int。

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.

推荐答案

检查我的 StoreGeneratedPattern blog post C $ C>。它解释了 Identity Computed 之间的一些差异。对于ID(PK)使用 StoreGeneratedPattern 时,正确的选项是如果您在应用程序中分配ID或 Identity 如果您在DB中分配ID。 计算的选项是无效的,因为在每个实体持久性(也在更新)中更改值时使用此选项,而不是ID。

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.

Identity Computed 之间的区别是执行SQL命令。如果属性为 Identity EF将在Insert后选择该值,并将其返回到您的应用程序。如果财产是计算的 EF将选择插入和更新后的值并将其返回到您的应用程序。

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.

编辑:

StoreGeneratedPattern.Identity 与DB中的Identity不相关。您不需要在DB中具有身份,您可以使用一些不同的技术(guid或触发器的默认值)设置ID,但您仍然需要 StoreGeneratedPattern.Identity 获取值

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.

一旦你使用 Identity Computed EF将始终遵循每个插入或更新与选择为db生成的列。如果没有它就不行。这些命令在单个往返数据库中执行,所以几乎没有性能影响。

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.

这篇关于实体框架中推荐的身份生成方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆