插入数据库之前对象的 ID (Linq to SQL)

发布于 2024-08-21 13:24:42 字数 266 浏览 4 评论 0原文

据我所知,在调用 SubmitChanges() 方法之前,Linq to SQL 实际上并不执行任何数据库命令(包括打开数据库连接)。如果是这样的话,我想提高一些方法的效率。我是否可以在插入对象之前检索该对象的ID?如果我可以在 ID 实际插入数据库之前知道 ID 的值,我宁愿不要调用 SubmitChanges() 两次。从逻辑的角度来看,只有打开与数据库的连接才能找出该值才有意义,但是是否还必须执行插入过程?

谢谢

From what I gather, Linq to SQL doesn't actually execute any database commands (including the opening of database connections) until the SubmitChanges() method is called. If this is the case, I would like to increase the efficiency of a few methods. Is it possible for me to retrieve the ID of an object before inserting it? I'd rather not call SubmitChanges() twice, if it's possible for me to know the value of the ID before it's actually inserted into the database. From a logical point of view, it would only makes sense to have to open a connection to the database in order to find out the value, but does an insertion procedure also have to take place?

Thanks

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

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

发布评论

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

评论(3

若沐 2024-08-28 13:24:42

解决此问题的常用技术是在应用程序层生成唯一标识符(例如 GUID)并将其用作 ID。这样您就不必在后续调用中检索 ID。

当然,使用 GUID 作为主键也有其缺点。如果您决定采用这种方式,请查找 COMB GUID。

The usual technique to solve this, is to generate a unique identifier in the application layer (such as a GUID) and use this as the ID. That way you do not have to retrieve the ID on a subsequent call.

Of course, using a GUID as a primary key can have it's drawbacks. If you decide to go this way look up COMB GUID.

忘年祭陌 2024-08-28 13:24:42

好吧,问题是:在插入数据库之前,您会以某种方式获取 id,并用它进行一些处理。同时另一个线程执行相同的操作,并获得相同的 ID,就会发生冲突。

即,我认为没有一种简单的方法可以做到这一点。

Well, here is the problem: You get somehow id BEFORE inserting to database, and do some processing with it. In the same time another thread does the same, and get's the same ID, you've got a conflict.

I.e. I don't think there is an easy way of doing this.

初见你 2024-08-28 13:24:42

我不一定推荐这样做,但已经看到这样做了。您可以使用存储过程和表来保存下一个 ID 的值,将自己的 ID 计算为整数。存储过程从表中选择值并将其返回,然后递增该值。该表将类似于以下

Create Table Keys(
name varchar(128) not null primary key,
nextID int not null
)

内容,在执行此操作之前需要注意的是,如果您选择然后分 2 个不同的批次进行更新,则可能会发生键冲突。这两个步骤都需要被视为原子事务。

I don't necessarily recommend this, but have seen it done. You can calculate your own ID as an integer using a stored procedure and a table to hold the value of the next ID. The stored procedure selects the value from the table to return it, then increments the value. The table will look something like the following

Create Table Keys(
name varchar(128) not null primary key,
nextID int not null
)

Things to note before doing this is that if you select and then update in 2 different batches you have potential key collision. Both steps need to be treated as an atomic transaction.

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