}
TransactionOption枚举类型支持5个COM+值(Disabled,NotSupported,Required,RequiresNew,Supported)
Disabled 忽略当前上下文中的任何事务。
NotSupported 使用非受控事务在上下文中创建组件。
Required 如果事务存在则共享事务,并且如有必要则创建新事务。
RequiresNew 使用新事务创建组件,而与当前上下文的状态无关。
Supported 如果事务存在,则共享该事务。
一般来说COM+中的组件需要Required 或Supported。当组件用于记录或查帐时RequiresNew 很有用,因为组件应该与活动中其他事务处理的提交或回滚隔离开来。
派生类可以重载基类的任意属性。如DataAccess选用Required,派生类仍然可以重载并指定RequiresNew或其他值。
COM+事务有手动处理和自动处理,自动处理就是在所需要自动处理的方法前加上[AutoComplete],根据方法的正常或抛出异常决定提交或回滚。
手动处理就是调用ContextUtil类中EnableCommit,SetComplete,SetAbort方法。
public string testTransaction()
{
try
{
ContextUtil.EnableCommit();
InsertARecord1();
InsertARecord2();
ContextUtil.SetComplete();
return "succeed!";
}
catch(Exception ex)
{
ContextUtil.SetAbort();
return "failed!";
}
}
public void InsertARecord1()
{
string strconn="workstation id=WEIXIAOPING;packet size=4096;user id=sa;initial catalog=Northwind;persist security info=False";
SqlConnection conn=new SqlConnection(strconn);
conn.Open();
SqlCommand command=new SqlCommand("insert into tbTree(Context,ParentID) values('北京',1)",conn);
command.ExecuteNonQuery();
conn.Close();
}
public void InsertARecord2()
{
string strconn="workstation id=WEIXIAOPING;packet size=4096;user id=sa;initial catalog=Northwind;persist security info=False";
SqlConnection conn=new SqlConnection(strconn);
conn.Open();
SqlCommand command=new SqlCommand("insert into tbTree(Context,ParentID) values('上海',1)",conn);
command.ExecuteNonQuery();
conn.Close();
}
在需要事务跨 MSMQ 和其他可识别事务的资源(例如,SQL Server 数据库)运行的系统中,只能使用 DTC 或 COM+ 事务,除此之外没有其他选择。DTC 协调参与分布式事务的所有资源管理器,
也管理与事务相关的操作。
这种做法的缺点是,由于存在 DTC 和 COM 互操作性开销,导致性能降低。
COM+事务处理的类必须强命名。