我是实际项目来拆出来做的案例,场景是比如我们在做电商网站时,在创建订单时的一系列操作,通常在创建订单时我们需要数据表的操作有:订单的表头(主表)、订单的详细、清空购物车、甚至是修改优惠劵的状态(在使用了优惠劵的时候),下面直接把执行事务的主方法直接贴出来:
public static bool CreateUserOrder(UserOrder model, string Ids)
{
List<string> SQLStringList = new List<string>();
List<DbParameter[]> Parameters = new List<DbParameter[]>();
StringBuilder strSql = new StringBuilder(); //添加OrderInfor
SqlParameter[] parameters1 = OrderInforDAL.BuildOrderInforAddParameter(model.UserId, model.OrderCode, Ids, ref strSql);
SQLStringList.Add(strSql.ToString());
Parameters.Add(parameters1); //添加UserOrder
SqlParameter[] parameters2 = BuildUserOrderAddParameter(model, ref strSql);
SQLStringList.Add(strSql.ToString());
Parameters.Add(parameters2); //清空购物车
SqlParameter[] parameters3 = BasketDetailDAL.BuildUpdateParameter(true, Ids, ref strSql);
SQLStringList.Add(strSql.ToString());
Parameters.Add(parameters3); //修改优惠劵状态
if (model.CouponId > )
{
SqlParameter[] parameters4 = CouponDAL.BuildUpdateParameter(model.CouponId, , model.OrderCode, ref strSql);
SQLStringList.Add(strSql.ToString());
Parameters.Add(parameters4);
} return access.ExecuteSqlTran(SQLStringList, Parameters, true);
}
接下来贴出两个个详细的方法作参考:
internal static SqlParameter[] BuildOrderInforAddParameter(int UserId, string OrderCode, string Ids, ref StringBuilder strSql)
{
strSql = new StringBuilder();
strSql.Append("INSERT INTO OrderInfor(");
strSql.Append("UserId,X_ProId,X_ProName,StockNum,BuyNum,UnitPrice,OrderCode,TotalPrice,IsOther)");
strSql.Append(" select UserId,X_ProId,X_ProName,StockNum,BuyNum,UnitPrice,@OrderCode,TotalPrice,IsOther from BasketDetail");
strSql.AppendFormat(" where UserId=@UserId and IsSubmit='false' and IsInquiry=2 and IsExpired=0 and BasketDetailId in ({0})", Ids);
SqlParameter[] parameters = {
new SqlParameter("@OrderCode", SqlDbType.NVarChar,),
new SqlParameter("@UserId", SqlDbType.Int)
};
parameters[].Value = OrderCode;
parameters[].Value = UserId;
return parameters;
}
internal static SqlParameter[] BuildUpdateParameter(int CouponId, int State, string OrderCode, ref StringBuilder strSql)
{
strSql = new StringBuilder();
strSql.Append("update Coupon set");
strSql.Append(" [State]=@State,OrderCode=@OrderCode");
strSql.AppendFormat(" where ID={0}", CouponId);
SqlParameter[] parameters = {
new SqlParameter("@State", SqlDbType.Int),
new SqlParameter("@OrderCode", SqlDbType.NVarChar,)
};
parameters[].Value = State;
parameters[].Value = OrderCode;
return parameters;
}