LINQ to SQL多次提交,我应该如何实现事务?
我有以下两个表表
1: PK(内) 总计计数(整数)
表 2: PK(内) FK(int)(与表1中PK的关系) 算一下
我在第一个表中插入一条记录,是为了得到一个PK。然后,当我从源获取数据并将其转储到表 2 中时,我将使用上一个表中的 PK 填充 FK。
我想在我的代码中实现事务。当插入表 2 失败时,我如何能够回滚表 1,因为表 1 本质上已经发出了提交?
我写了一些代码来帮助说明我在做什么,
using (DeviceDataContext context = new DeviceDataContext())
{
tgdd = new Data();
context.Datas.InsertOnSubmit(tgdd);
context.SubmitChanges();
int pk = tgdd.PK;
int count = 0;
foreach (…)
{
count += 1;
tgd = new Data2();
tgd.FK = pk;
tgd.count = count;
context.Datas2.InsertOnSubmit(tgd); //if this crashes, I want to roll
//back what happened to table 1(Datas)
}
}
我很快就写了这段代码,所以如果有逻辑错误,请忽略。
那么交易会帮助我做我想做的事吗?
I have the following two tables
Table 1:
PK (int)
TotalCount (int)
Table 2:
PK (int)
FK (int)(relation with PK in Table 1)
Count
I insert a record into the first table, in order to get a PK. Then when I'm grabbing data from a source and dumping it into Table 2, I'm populating FK with the PK from the previous table.
I would like to implement transactions into my code. How would I be able to roll back table 1 when inserting into table 2 fails, since table 1 is already issued a commit essentially?
I wrote a little code to help illustrate what I'm doing
using (DeviceDataContext context = new DeviceDataContext())
{
tgdd = new Data();
context.Datas.InsertOnSubmit(tgdd);
context.SubmitChanges();
int pk = tgdd.PK;
int count = 0;
foreach (…)
{
count += 1;
tgd = new Data2();
tgd.FK = pk;
tgd.count = count;
context.Datas2.InsertOnSubmit(tgd); //if this crashes, I want to roll
//back what happened to table 1(Datas)
}
}
I wrote this code quickly, so if there's logical errors, please ignore.
So will transactions help me do what I want?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
通常,您应该在 Data2 上有一个导航属性,您可以将其设置为 Data1 实例:
这样,这不仅可以在单个事务范围内完成,而且还可以在单个数据库往返中完成。
如果您无法使用导航属性来做到这一点,那么使用 TransactionScope 是次佳选择。
Typically you should have a navigation property on Data2 that you can set to your Data1 instance:
That way this can not only be done in a single transaction scope, but also in a single database roundtrip.
If you can't do this using a navigation property, using a TransactionScope is the next-best thing.
将“using (DeviceDataContext context = new DeviceDataContext())”包装在 TransactionScope 中:
如果 InsertOnSubmt 失败,事务将自动回滚。
Wrap your "using (DeviceDataContext context = new DeviceDataContext())" in a TransactionScope:
If the InsertOnSubmt fails, the transaction will automatically be rolledback.