我们是否必须在 LinqToSql 应用程序中使用 GUID 来唯一标识对象
我继承了一个 LinqToSql 应用程序,该应用程序使用对象的 GUID 键。 我宁愿使用传统的身份字段——人们更容易使用、理解和交流。然而,有一些业务逻辑要求应用程序在将唯一对象保存到数据库之前识别它们,这就是首先使用 GUID 的原因。
我们遇到的另一个问题是碎片索引 - AFAIK 我们无法在 .Net 代码中创建顺序 GUID。
由于这是我在 LinqToSql 中的第一次练习,我想知道其他人如何解决这个问题。
顺便说一句,不需要组合多个服务器之间的数据 - 这是我过去使用 GUID 密钥的主要原因(唯一)。
I have inherited a LinqToSql application which is making use of GUID keys for objects.
I'd rather use conventional identity fields - much easier for people to use, understand and communicate. However there is some business logic that requires the application to identify unique objects before they're persisted to the DB which is why GUIDs where used in the first place.
Another issue we're having is with fragmented indexes - AFAIK we can't create sequential GUIDs in .Net code.
As this is my first exercise in LinqToSql I'd like to know how others have addressed this issue.
BTW there is no need for the data between multiple servers to be combined - the main (only) reason that I've used GUID keys in the past.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,您不必使用 Guid,您可以使用您想要的任何键类型。
如果您对 Guid 感到困惑,请考虑让数据库通过为 pk 字段
newsequentialid()
设置默认绑定来按顺序生成它们。这至少会消除聚集索引中的碎片。如果执行此操作,您需要对 .dbml 进行一些修改。在 .dbml 中的关键字段Auto generated Value = true
和Auto-Sync = OnInsert
至于在插入数据库之前生成值,我没有看到使用身份字段如何帮助您。您仍然需要插入数据库才能可靠地获取正确的值。 (身份列将具有与上面相同的自动生成/自动同步设置)
Ints 或 Guid,您应该能够将插入包装在事务中,插入记录,获取新的键值,运行业务逻辑,如果失败则回滚新插入的记录。
No, you don't have to use Guids, you can use any key type you'd like.
If you are stuck with Guids consider having the database generate them sequentially for you by making the default binding for the pk field
newsequentialid()
. This will eliminate fragmentation in your clustered index at least. You need to make a few modifications to the .dbml if you do this. On the key field in the .dbmlAuto Generated Value = true
andAuto-Sync = OnInsert
As far as generating the value before you insert to the database I don't see how using an identity field helps you. You will still have to insert to the database to reliably get the correct value. (Identity columns will have the same Autogenerated/Autosync settings as above)
Ints or Guids, you should be able to wrap the insert in a transaction, insert the record, grab the new key value, run your business logic and if it fails roll back the newly inserted record.