EFCore 中执行存储过程返回DataSet DataTable

在项目中由于需求,需要返回复杂的数据,需要执行存储过程,但是在DONETCORE2.0中,看官网文档执行的sql的有点操蛋,满足不了需求,就想到了ADO.NET 

于是找资料,也没有合适的,就动手自己封装了一个。代码如下;

 1 public static class ExtendDbRepository
 2     {
 3         public static DataSet SqlQuery(this Db db, string spName, params SqlParameter[] paramsters)
 4         {
 5             SqlConnection connection = db.Database.GetDbConnection() as SqlConnection;
 6             SqlDataAdapter adapter = null;
 7             DataSet set = null;
 8             using (SqlCommand command = new SqlCommand(spName, connection))
 9             {
10                 command.CommandType = CommandType.StoredProcedure;
11                 command.CommandText = spName;
12                 command.Parameters.AddRange(paramsters);
13                 adapter = new SqlDataAdapter(command);
14 
15                 set = new DataSet();
16                 adapter.Fill(set);
17                 adapter.SelectCommand.Parameters.Clear();
18                 adapter.Dispose();
19                 command.Parameters.Clear();
20                 command.Dispose();
21                 connection.Close();
22                 connection.Dispose();
23                 return set;
24             }
25         }
26 
27         public static IEnumerable<TElement> SqlQuery<TElement>(this Db db, string sql, params object[] parameters) where TElement : new()
28         {
29             var connection = db.Database.GetDbConnection();
30             using (var cmd = connection.CreateCommand())
31             {
32                 db.Database.OpenConnection();
33                 cmd.CommandText = sql;
34                 cmd.CommandType = System.Data.CommandType.StoredProcedure;
35                 cmd.Parameters.AddRange(parameters);
36                 var dr = cmd.ExecuteReader();
37                 var columnSchema = dr.GetColumnSchema();
38                 var data = new List<TElement>();
39                 while (dr.Read())
40                 {
41                     TElement item = new TElement();
42                     Type type = item.GetType();
43                     foreach (var kv in columnSchema)
44                     {
45                         var propertyInfo = type.GetProperty(kv.ColumnName);
46                         if (kv.ColumnOrdinal.HasValue && propertyInfo != null)
47                         {
48                             //注意需要转换数据库中的DBNull类型
49                             var value = dr.IsDBNull(kv.ColumnOrdinal.Value) ? null : dr.GetValue(kv.ColumnOrdinal.Value);
50                             propertyInfo.SetValue(item, value);
51                         }
52                     }
53                     data.Add(item);
54                 }
55                 dr.Dispose();
56                 return data;
57             }
58         }
59     }

 

posted @ 2019-04-03 11:45  垣瑾  阅读(3697)  评论(1编辑  收藏  举报