ASP.NET Entity FrameWork中:
int flag = -1; if (this.URPmanagementEntities1.Connection.State != System.Data.ConnectionState.Open) { this.URPmanagementEntities1.Connection.Open(); } var trans = this.URPmanagementEntities1.Connection.BeginTransaction(); try { //这里进行添加数据操作 begin
urpentity.AddToT_ArticleCatalog(articlecatalog); urpentity.SaveChanges();
T_Article article=new T_Article();
article.CatalogID=articlecatalog.id;
urpentity.AddToT_Article(article); this.DbEntity.SaveChanges(); trans.Commit(); flag = 0; } catch (Exception ex) { trans.Rollback(); throw ex; } finally { if (this.DbEntity.Connection.State != System.Data.ConnectionState.Closed) { this.DbEntity.Connection.Close();
} } return flag;
LinqToSql中使用事务类似:
事务的使用有两种方法:
如果不想使用默认的事务设置,比如想改变事务的孤立级别,我们可以给DataContext的Transaction属性赋值,以此使用自定义的事务。
ctx.Transaction = ctx.Connection.BeginTransaction(System.Data.IsolationLevel.Serializable); try { ctx.SubmitChanges(); ctx.Transaction.Commit(); } catch { ctx.Transaction.Rollback(); throw; } finally { ctx.Transaction = null; }
最后一种方式是通过TransactionScope创建轻量级事务,就像在ADO.NET中使用一样:
using (TransactionScope scope = new TransactionScope()) { ctx.SubmitChanges(); scope.Complete(); }