如何回滚事务与LINQ to SQL相关? [英] How is rolling back transaction related to LINQ to SQL?

查看:162
本文介绍了如何回滚事务与LINQ to SQL相关?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



假设我提取了一些数据,我修改了它们,我提交了更改(可选步骤)和我回滚事务。



但我发现这是一半 - LINQ DataContext将保留更改的数据!我使用TransactionScope和DataContext.Transaction测试了这个。在这两种情况下,我都有相同的行为。



一种解决方法是在回滚后重新创建DataContext(但这会导致其他问题,如缓存数据和处理嵌套事务)手动丢弃DataContext中的更改。



问题



那么我失踪了什么? LINQ to SQL不适合事务吗?如何使用交易,以便他们真的回滚更改?



示例



  MyTable record = null; 

db.Connection.Open();
using(db.Transaction = db.Connection.BeginTransaction())
{
record = db.MyTable.First();
record.BoolField =!record.BoolField; // changed
db.SubmitChanges();
db.Transaction.Rollback();
}


解决方案

被认为是工作单位。如何以粒度 来做,这取决于您 - 它可能是一个页面请求,或单个操作;但是 - 如果您遇到异常(或几乎任何意外情况) - 停止 ;放弃数据上下文和回滚。回滚后,您的数据上下文会被混淆,因此只是不保存



不要保持数据上下文超过必要。它不打算作为一个app级的数据缓存。


The question is solely about rolling back the changes, not commiting.

Let's say I fetch some data, I change them, I submit changes (optional step) and I roll back transaction. Wherever you look every author writes, this cancels the changes.

But I found out that is half true -- LINQ DataContext will keep the changed data! I tested this using TransactionScope and DataContext.Transaction. In both cases I got the same behaviour.

A workaround would be to recreate DataContext after roll back (however this leads to other problems like caching data and handling nested transactions) or manually discarding the changes in DataContext. Nevertheless those are just workarounds.

Questions

So what am I missing? Is LINQ to SQL not suited for transactions? How to use transactions so they would REALLY roll back changes?

Example

                MyTable record = null;

                db.Connection.Open();
                using (db.Transaction = db.Connection.BeginTransaction())
                {
                        record = db.MyTable.First();
                        record.BoolField = !record.BoolField; // changed
                        db.SubmitChanges();
                        db.Transaction.Rollback();
                }

解决方案

A data-context should be considered as a unit-of-work. How granular you make that is up to you - it could be a page request, or a single operation; but - if you get an exception (or pretty much anything unexpected) - stop; abandon the data-context and rollback. After a rollback, your data-context is going to be confused, so just don't keep it.

Additionally; don't keep a data-context for longer than necessary. It is not intended as an app-long data cache.

这篇关于如何回滚事务与LINQ to SQL相关?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆