Asp.net USES instance code for transactions in a three tier architecture
- 2020-05-17 05:16:35
- OfStack
I have been in touch with layer 3 for a while, so I have a similar understanding of level 1. Some time ago, I was thinking about how to use transactions in layer 3 and where to put them. Sqlherper? DAL? BLL? . Then I was crazy about baidu, and failed several times (because what I did was a small project, and it didn't matter much if I didn't do anything). Today, when I checked again, I had a good look at the discussion on csdn. http: / / topic. csdn. net/u / 20091101/19 / f21697d7-8 eb3 f0c - 4-8 e59 - d0fe2f0b04b0. html, combining the predecessors and the opinions of the experts, their changed one. My idea is to write the transaction logic in the business logic layer, and the database is also processed in the SQLHELPER, BLL layer through the transaction SqlTransaction transfer value to access DAL, and then access Sqlhelper. Next comes the code for the blocks.
Sqlhelper:
DAL:
BLL:
The above code passed in the test, if you want to be used in the real project, please modify it and then use it. There are my level 1, please forgive me if I can't write it. Your guidance and corrections are welcome.
Sqlhelper:
private static SqlConnection Cnn = new SqlConnection(DbConfig.ConnectionString);
#region interpretation SqlConnection Whether to open the connection or not And open
/// <summary>
/// interpretation SqlConnection Whether to open the connection or not And open
/// </summary>
/// <returns> return SqlConnection</returns>
private static SqlConnection GetCnn()
{
if (Cnn.State == ConnectionState.Closed)
{
Cnn.Open();
}
return Cnn;
}
#endregion
#region Close the database connection
/// <summary>
/// Close the database connection
/// </summary>
public static void CloseCnn()
{
Cnn.Close();
}
#endregion
#region produce 1 Two transactions and start
/// <summary>
/// produce 1 Two transactions and start
/// </summary>
/// <returns> Returns this transaction </returns>
public static SqlTransaction BeginTransaction()
{
SqlTransaction tran = GetCnn().BeginTransaction();
return tran;
}
#endregion
DAL:
public bool test(int i,SqlTransaction tran)
{
string sql = "insert into [test]([item]) values(@i)";
SqlParameter[] paras=new SqlParameter[]{new SqlParameter("@i",i)};
return sqlhelper.ExecutenQuery(sql, paras, CommandType.Text, tran)>0;
}
BLL:
UserDAO userdao = new UserDAO();
public bool test()
{
using (SqlTransaction tran = SQLHelper.BeginTransaction())
{
try
{
userdao.test(2, tran);
userdao.test(3, tran);
tran.Commit(); return true;
}
catch
{
tran.Rollback();
return false;
}
finally
{
SQLHelper.CloseCnn();// Close the database connection
}
}
}
The above code passed in the test, if you want to be used in the real project, please modify it and then use it. There are my level 1, please forgive me if I can't write it. Your guidance and corrections are welcome.