• ASP.NET页面级别的事务


    ASP.NET事务可以说是在.NET平台上事务实现方式最简单的一种,你仅仅需要一行代码即可。在aspx的页面声明中加一个额外的属性,即事务属性Transaction="Required",它有如下的值:Disabled(默认)、NotSupported、Supported、Required和RequiresNew,这些设置和COM+及企业级服务中的设置一样,典型的一个例子是如果你想在页面上下文中运行事务,那么要将其设置为Required。如果页面中包含有用户控件,那么这些控件也会包含到事务中,事务会存在于页面的每个地方。

    代码示例:

    页面声明Transaction="Required":

    <%@ Page Transaction="Required"  Language="C#" AutoEventWireup="true"

    CodeBehind="WebForm3.aspx.cs" Inherits="WebApplication4.WebForm3" %>

    页面引用:using System.EnterpriseServices;。

    然后,数据操作代码:

    protected void Button1_Click(object sender, EventArgs e)

    {

        try

        {

            Work1();

            Work2();

            ContextUtil.SetComplete();   //提交事务

        }

        catch (System.Exception except)

        {

            ContextUtil.SetAbort();      //撤销事务

            Response.Write(except.Message);

        } 

    private void Work1()

    {

        string conString = "data source=127.0.0.1;database=codematic;user id=sa;

          password=";

        SqlConnection myConnection = new SqlConnection(conString);

        string strSql = "Insert Into P_Category(CategoryId,Name)values('1',

          'test1')";

        SqlCommand myCommand = new SqlCommand(strSql, myConnection);

        myConnection.Open();

        int rows = myCommand.ExecuteNonQuery();

        myConnection.Close();

    }

    private void Work2()

    {

        string conString = "data source=127.0.0.1;database=codematic;user id=sa;

          password=";

        SqlConnection myConnection = new SqlConnection(conString);

        string strSql = "Insert Into P_Category(CategoryId,Name)values('2',

          'test2')";

        SqlCommand myCommand = new SqlCommand(strSql, myConnection);

        myConnection.Open();

        int rows = myCommand.ExecuteNonQuery();

        myConnection.Close();

    }

    ContextUtil是用于获取 COM+ 上下文信息的首选类。由于此类的成员全部为static,因此在使用其成员之前不需要对此类进行实例化。

    ASP.NET页面事务的优势和限制如下。

    l  优势:实现简单,不需要额外的编码。

        l限制:页面的所有代码都是同一个事务,这样的事务可能会很大,而也许我们需要的是分开的、小的事务实现在Web层

  • 相关阅读:
    新建项目
    Pandas常用操作
    Codeforces Round #764 (Div. 3)(CF1624)题解
    求1到n在模mod意义下的逆元
    [IOI2000] 回文字串 / [蓝桥杯 2016 省] 密码脱落(dp)
    持续集成:Jenkins Pipeline共享库定义和使用
    持续集成:Jenkins API使用方法详细介绍
    持续集成:Jenkins Pipeline语法介绍
    持续集成:Jenkins邮件通知配置方法介绍
    使用facebookwda进行iOS APP自动化测试
  • 原文地址:https://www.cnblogs.com/soundcode/p/2056871.html
Copyright © 2020-2023  润新知