实体框架在插入数据库时​​是否保留顺序?

发布于 2024-07-20 07:27:21 字数 239 浏览 8 评论 0原文

我们计划在 SQL Server 数据库中使用标识列。 目前我们正在使用 guid 来生成唯一的 id,但事实证明顺序是相关的,因此我们考虑切换到标识列。

由于排序是相关的,我们希望确保将对象添加到实体上下文的顺序也是它们插入数据库的顺序。 这是相关的,因为 sql server 将为标识列生成值。

这是实体框架保证的吗? 如果不是,那么为从不同进程更新的数据库生成自己的唯一整数 ID 的有效解决方案是什么。

We plan on using identity columns in our sql server database. Currently we are using guids to generate unique ids, but it turns out that the ordering is relevant so we consider switching to identity columsn.

Since ordering is relevant we want to make sure that the order in which we add objects to the entity context is also the order in which they are inserted into the database. This is relevant since sql server will be generating values for the identity column.

Is this guaranteed by the entity framework? If not, what is an efficient solution to generating your own unique integer ids for a database that is being updated from different processes.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

携余温的黄昏 2024-07-27 07:27:21

我只是在这里猜测(虽然应该很容易测试),但我不认为 EF 可以保证顺序。 我非常确定内部结构基于 IEnumerable 类型,可能是一个 List,它们只是在插入期间枚举,并且据我所知,枚举不能保证每次都按相同的顺序。

相反,我会在数据库表中添加一个专用的“排序顺序”列,并在那里获取它。

I am just guessing here (although it should be pretty easy to test), but I don't think EF can guarantee the order. I am pretty sure that the internal structure is based on an IEnumerable type, probably a List, which are just enumerated during insert, and enumeration is as far as I know not guaranteed to be in the same order every time.

I would instead add a dedicated "sort order" column to your database table and take it form there.

帅哥哥的热头脑 2024-07-27 07:27:21

我不会依赖插入顺序作为您返回的记录的顺序。 当然,它在大多数情况下都可以工作,但是如果您需要在某处插入一行怎么办? 我想说你最好的选择是添加一个序数列,并根据你希望返回的内容主动为每一行生成序数。

I wouldn't rely on the insert order as the order of your records returned. Sure, it'll work most of the time, but what if you ever need to insert a row somewhere? I'd say your best bet is to add an ordinal column and actively generate ordinals for each row as you'd like them to be returned.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文