C# / Linq-to-sql - 在 insertonsubmit 上锁定 datacontext.Table
我目前正在我的数据访问类上创建一个方法,该方法将向数据库插入一个实体对象,并且我希望随后获得最新插入的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
无需锁定您的桌子。
在您插入
person
.SubmitChanges() 时,LINQ-to-SQL 会自动使用数据库中的身份填充您的ID
字段>。需要注意的是,您的数据库和 L2S 实体都必须将您的
ID
字段定义为身份。在您的Person
实体上,您应该将该字段定义为主键、IsDbGeneerated=true
、UpdateCheck=never
,并拥有正确的数据库类型。提交后,您应该能够从
Person
实体中简单地检索ID
: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 yourperson
.The caveat is that both your database and L2S entity must define your
ID
field as an identity. On yourPerson
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 yourPerson
entity:我不确定这是否是您关心的问题,但如果您使用 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