数据库回滚操作
/// ///事务 ///
internal SqlTransaction Transaction { get; set; }
public string EditEmployee(OrgEmployee employee, Guid departmentGuid, Guid companyGuid, bool isPIC)
{
SqlPlus plus = new SqlPlus();
string result = string.Empty;
using (SqlConnection conn = plus.GetConnection())
{
conn.Open();
this.Transaction = conn.BeginTransaction();//开启事物操作
try {
this.EditEmployee(employee);
this.EditEmp2Dept(employee.EmployeeGuid, departmentGuid, companyGuid, isPIC);
this.Transaction.Commit();
}
catch (Exception ex)
{
result = ex.Message; Transaction.Rollback(); conn.Close();
}
}
return result;
}
private void EditEmp2Dept(Guid employeeGuid, Guid departmentGuid, Guid companyGuid, bool isPIC)
{
SqlParameter[] prams =
{
Database.MakeInParam("@EmployeeGuid", System.Data.SqlDbType.UniqueIdentifier, 16, employeeGuid), Database.MakeInParam("@DepartmentGuid", System.Data.SqlDbType.UniqueIdentifier, 16, departmentGuid), Database.MakeInParam("@CompanyGuid", System.Data.SqlDbType.UniqueIdentifier, 16, companyGuid),
Database.MakeInParam("@IsPIC", System.Data.SqlDbType.Bit, 1, isPIC)
};
if (Transaction == null)
{
new SqlPlus().ExecuteNonQuery(CommandType.StoredProcedure, "up_Emp2DeptEdit", prams);
}
else
{
new SqlPlus().ExecuteNonQuery(Transaction, CommandType.StoredProcedure, "up_Emp2DeptEdit", prams);
}
}
public int ExecuteNonQuery(SqlTransaction trans, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, commandParameters);
int val = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
return val;
}
/// <summary>
/// 执行SQL命令
/// </summary>
private void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType cmdType, string cmdText, SqlParameter[] cmdParms)
{
if (conn.State != ConnectionState.Open)
conn.Open();
cmd.Connection = conn;
cmd.CommandText = cmdText;
cmd.CommandTimeout = 120;
if (trans != null)
cmd.Transaction = trans;
cmd.CommandType = cmdType;
if (cmdParms != null)
{
foreach (SqlParameter parm in cmdParms)
cmd.Parameters.Add(parm);
}
}