C# / Linq-to-sql - 在 insertonsubmit 上锁定 datacontext.Table

发布于 2024-12-11 18:59:31 字数 377 浏览 0 评论 0原文

我目前正在我的数据访问类上创建一个方法,该方法将向数据库插入一个实体对象,并且我希望随后获得最新插入的 ID...我已经这样做了,但后来我想知道什么如果该方法同时被调用两次,会发生这种情况吗?它会返回错误的 ID 吗?

因此,作为解决方案,我决定在数据上下文上锁定表:

lock(dataContext.Persons)
{
    InsertOnSubmit(person);
    dataContext.SubmitChanges();
}

但我确实觉得这是不合适的...我的意思是,表不大,数据上下文提交更改不会花费很长时间...所以我的问题是,这样锁定会遇到什么样的麻烦?

PS:如果我的问题不够清楚,请告诉我,我会编辑它!

I'm currently creating a method on my data access class that is going to insert an entity object to the database and I was expecting to get the latest inserted ID afterwards... and I've already done that but then I was wondering what would happend if the method somehow gets invoked twice at the same time, would it return the wrong ID?

So as a work around to that I decided to Lock the table on my datacontext:

lock(dataContext.Persons)
{
    InsertOnSubmit(person);
    dataContext.SubmitChanges();
}

but I do feel like this is inappropriate... I mean, the table isnt big and it wont take long to the datacontext to submit changes... So my question is, what kind of trouble would I run into by locking it like that?

PS: Let me know if my question was not clear enough and I'll edit it!

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

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

发布评论

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

评论(2

〗斷ホ乔殘χμё〖 2024-12-18 18:59:31

无需锁定您的桌子。

在您插入 person.SubmitChanges() 时,LINQ-to-SQL 会自动使用数据库中的身份填充您的 ID 字段>。

需要注意的是,您的数据库和 L2S 实体都必须将您的 ID 字段定义为身份。在您的 Person 实体上,您应该将该字段定义为主键、IsDbGeneerated=trueUpdateCheck=never,并拥有正确的数据库类型。

提交后,您应该能够从 Person 实体中简单地检索 ID

dataContext.Persons.InsertOnSubmit(person);
dataContext.SubmitChanges();
var id = person.ID; // now has the database generated identity.

There is no need to lock your table.

LINQ-to-SQL will automatically populate your ID field with the identity from the database upon your call to .SubmitChanges() when you insert your person.

The caveat is that both your database and L2S entity must define your ID field as an identity. On your Person entity, you should have that field defined as the primary key, IsDbGenerated=true, UpdateCheck=never, and have the correct database type.

Once you submit, you should be able to simply retrieve the ID from your Person entity:

dataContext.Persons.InsertOnSubmit(person);
dataContext.SubmitChanges();
var id = person.ID; // now has the database generated identity.
晨敛清荷 2024-12-18 18:59:31

我不确定这是否是您关心的问题,但如果您使用 TransactionScope,您可以传入一个将处理多个事务的 TransactionOption。

查看 TransactionOption.Isolationlevel

Im not sure if this is part of your concerns, but if you use TransactionScope you can pass in a TransactionOption that will deal with multiple transactions.

Check out TransactionOption.Isolationlevel

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