【发布时间】:2015-04-25 06:30:12
【问题描述】:
我有 3 张桌子:
master_upload(主上传具有名为 master_upload_id 的自动递增主键)master_upload_files(由2列组成,参考上表中的master_upload_id)master_upload_tags(同第二个)
在第 2 表和第 3 表中,第 1 表可以有多行。
现在要插入第二张和第三张表,我需要一个 master_upload_id,我只有在插入后才能得到它。因此,我必须至少致电db.SubmitChanges 3 次。如果第二个和第三个表有多个值,我必须为这两个表中的每一行调用db.SubmitChanges。但有时由于某些规则违规,在第二或第三表中的插入可能会失败。
因此,在这些情况下我需要回滚。我该怎么做?
我以前通过 SQL Server 存储过程来完成这些事情,但现在我需要在 LINQ 中完成。
// Here is my code sample
using (dbDataContext db = new dbDataContext())
{
db.master_uploads.InsertOnSubmit(mu);// toget mu.upload_id
try
{
db.SubmitChanges();
master_upload_file mf = new master_upload_file();
mf.master_upload_id = mu.upload_id;
mf.upload_file_id = uploadedfile.file_id;
db.master_upload_files.InsertOnSubmit(mf);
for (int i = 0; i < tags.Length; i++)
{
master_upload_tag mt = new master_upload_tag();
mt.master_upload_id = mu.upload_id;
mt.tag = tags[i];
db.master_upload_tags.InsertOnSubmit(mt);
}
db.SubmitChanges();
gtu.writetext("0",context);
}
catch (Exception)
{
gtu.writetext("1:File Upload Add Error", context);
}
}
我使用的是 SQL Server 2008。
谢谢
【问题讨论】:
-
你现在应该知道必须显示代码了。
-
我已添加代码
-
TransactionScope 应该会有所帮助。您需要运行分布式事务协调器服务,但我认为这就是您要寻找的。span>
标签: c# sql-server database linq