(LINQ 学习系列)(8)Linq教程实例: 事务处理
Linq to sql在提交更新的时候默认会创建事务,一部分修改发生错误的话其它修改也不会生效
下面是插入2个表中的数据进行事务处理
private void TransAdd()
{
DataClasses1DataContext db = new DataClasses1DataContext(sqlconStr);
if (db.Connection != null) db.Connection.Open();
DbTransaction tran = db.Connection.BeginTransaction();
db.Transaction = tran;
try
{
student mystudent = new student();
mystudent.StudentName = "LiX";
mystudent.Sex = "Man";
mystudent.Old = 17;
Oclass myClass = new Oclass();
myClass.StudentName = "LiX";
myClass.Class = "Win7";
db.ObjectTrackingEnabled = true;
db.student.InsertOnSubmit(mystudent);
db.Oclass.InsertOnSubmit(myClass);
db.SubmitChanges();
tran.Commit();
}
catch(Exception ex)
{
tran.Rollback();
}
}
{
DataClasses1DataContext db = new DataClasses1DataContext(sqlconStr);
if (db.Connection != null) db.Connection.Open();
DbTransaction tran = db.Connection.BeginTransaction();
db.Transaction = tran;
try
{
student mystudent = new student();
mystudent.StudentName = "LiX";
mystudent.Sex = "Man";
mystudent.Old = 17;
Oclass myClass = new Oclass();
myClass.StudentName = "LiX";
myClass.Class = "Win7";
db.ObjectTrackingEnabled = true;
db.student.InsertOnSubmit(mystudent);
db.Oclass.InsertOnSubmit(myClass);
db.SubmitChanges();
tran.Commit();
}
catch(Exception ex)
{
tran.Rollback();
}
}