实体框架在插入数据库时是否保留顺序?
我们计划在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我只是在这里猜测(虽然应该很容易测试),但我不认为 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.
我不会依赖插入顺序作为您返回的记录的顺序。 当然,它在大多数情况下都可以工作,但是如果您需要在某处插入一行怎么办? 我想说你最好的选择是添加一个序数列,并根据你希望返回的内容主动为每一行生成序数。
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.