C# 委托

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
public T Query<T>(int id) where T : BaseModel
       {
           Type type = typeof(T);
           string columnString = string.Join(",", type.GetProperties().Select(p => $"[{p.GetColumnName()}]"));
           string sql = $"SELECT {columnString} FROM [{type.Name}] WHERE Id=@Id";
           T t = default(T);
           DataTable dt = new DataTable();
 
           Func<SqlCommand, T> func = (SqlCommand command) =>//1 将要执行的先准备好
           {
               SqlParameter para = new SqlParameter("@Id", id);//3 func.invoke(command) 执行这里并返回
               command.Parameters.Add(para);
               SqlDataAdapter adapter = new SqlDataAdapter(command);
               //SqlDataReader reader = command.ExecuteReader();
               //List<T> list = this.ReaderToList<T>(reader);
               adapter.Fill(dt);
               List<T> list = ConvertToList<T>(dt);
               T tResult = list.FirstOrDefault();
               return tResult;
           };
           t = ExcuteSql<T>(sql, func);
           return t;
       }
 
private T ExcuteSql<T>(string sql, Func<SqlCommand, T> func)
       {
           using (SqlConnection conn = new SqlConnection(strConn))
           {
               using (SqlCommand command = new SqlCommand(sql, conn))
               {
                   conn.Open();
                   SqlTransaction sqlTransaction = conn.BeginTransaction();
                   try
                   {
                       command.Transaction = sqlTransaction;
                       T tResult = func.Invoke(command);//2执行前面准备好的。
                       sqlTransaction.Commit();
                       return tResult;
                   }
                   catch (Exception ex)
                   {
                       sqlTransaction.Rollback();
                       throw;
                   }
               }
           }
       }

  

posted @   孤海飞雁  阅读(8)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具
· AI 智能体引爆开源社区「GitHub 热点速览」
点击右上角即可分享
微信分享提示