使用 SubmitChanges 创建 LINQ 事务
因此,我尝试使用 LINQ to SQL 进行事务处理。我读到,如果我使用 SubmitChanges()
,它将创建一个事务并执行所有内容,如果出现异常,所有内容都会回滚。我需要使用多个 SubmitChanges()
吗?我正在使用类似此代码的代码,但它不起作用,因为它没有在第一个表上保存任何数据..(我需要它的子表的 ID)。
如果我确实在第一个 InsertOnSubmit
之后使用另一个 SubmitChanges()
,它不会失去事务的概念吗?
myDataContext db = new myDataContext();
Process openProcess = new Process();
openProcess.Creation = DateTime.Now;
openProcess.Number = pNumber;
//Set to insert
db.Process.InsertOnSubmit(openProcess);
Product product = new Product();
product.Code = pCode;
product.Name = pName;
product.Process_Id = openProcess.Id;
//Submit all changes at once?
db.SubmitChanges();
So, I'm trying to make a transaction with LINQ to SQL. I read that if I use SubmitChanges()
, it would create a transaction and execute everything and in case of an exception everything would be rolled back. Do I need to use MULTIPLE SubmitChanges()
? I'm using something like this code and it isn't working because it isn't saving any data on the first table.. (I need it's ID for the children table).
If I do use another SubmitChanges()
right after the first InsertOnSubmit
doesn't it lose the idea of a transaction?
myDataContext db = new myDataContext();
Process openProcess = new Process();
openProcess.Creation = DateTime.Now;
openProcess.Number = pNumber;
//Set to insert
db.Process.InsertOnSubmit(openProcess);
Product product = new Product();
product.Code = pCode;
product.Name = pName;
product.Process_Id = openProcess.Id;
//Submit all changes at once?
db.SubmitChanges();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
TransactionScope
使整个事情成为事务性的,例如,如果在调用
scope.Complete()
之前抛出异常,那么整个事情将被回滚。You can make the whole thing transaciotnal using a
TransactionScope
e.g.If an exception is thrown before
scope.Complete()
is called then the whole thing will be rolled back.问题是,当更改提交到数据库时,进程的 ID 就被设置了。因为您在将流程 ID 分配给产品的行 (
product.Process_Id = openProcess.Id;
) 之后提交更改。正确的方法是使用从 PRODUCT 到 PROCESS 的外键正确设置数据库,并使用
Product
上的导航属性Process
将流程分配给产品。代码如下所示:
由于
Process
是Product
的导航属性,因此您不需要插入Process
。它将自动插入,因为您插入了“父级” -Product
。The problem is, that the ID of your process is set when the changes are submitted to the database. Because you submit the changes after the line where you assign the process id to the product (
product.Process_Id = openProcess.Id;
).The correct way to do this would be to correctly setup your database with a foreign key from PRODUCT to PROCESS and use the navigation property
Process
onProduct
to assign the process to the product.The code would look like this:
Because
Process
is a navigation property ofProduct
, you don't need to insert theProcess
. It will be inserted automatically, because you insert the "parent" - theProduct
.