DbUtility中的方法ExecuteDataTableAsync()得到的是一个DataTable,而我们常见的情况下,我们需要的不是DataTable,而是List或IList,所以现在需要考虑把DataTable转成List或IList,目前暂时有三种方案:

方案1:用动软生成代码:

  1. public static List<Roles> GetRoleses(DataTable dt)
  2. {
  3. List<Roles> list = new List<Roles>();
  4. )
  5. list.AddRange(from DataRow dataRow in dt.Rows select DataRowToModel(dataRow));
  6. return list;
  7. }
  8.  
  9. /// <summary>
  10. /// 得到一个对象实体
  11. /// </summary>
  12. private static Roles DataRowToModel(DataRow row)
  13. {
  14. Roles model = new Roles();
  15. if (row != null)
  16. {
  17. if (row["RoleID"] != null && row["RoleID"].ToString() != "")
  18. {
  19. model.RoleID = new Guid(row["RoleID"].ToString());
  20. }
  21. if (row["RoleName"] != null)
  22. {
  23. model.RoleName = row["RoleName"].ToString();
  24. }
  25. if (row["Description"] != null)
  26. {
  27. model.Description = row["Description"].ToString();
  28. }
  29. if (row["TaskMask"] != null)
  30. {
  31. model.TaskMask = row["TaskMask"].ToString();
  32. }
  33. if (row["RoleFlags"] != null && row["RoleFlags"].ToString() != "")
  34. {
  35. model.RoleFlags = int.Parse(row["RoleFlags"].ToString());
  36. }
  37. }
  38. return model;
  39. }

循环遍历100W次,大约用时:14460毫秒。

方案2:用MVC.Net提供的反射方案:

  1. public static IList<T> ConvertToModel<T>(this DataTable dt) where T : class, new()
  2. {
  3. // 定义集合
  4. IList<T> ts = new List<T>();
  5. // 获得此模型的类型
  6. Type type = typeof(T);
  7. string tempName = "";
  8. foreach (DataRow dr in dt.Rows)
  9. {
  10. T t = new T();
  11. // 获得此模型的公共属性
  12. PropertyInfo[] propertys = t.GetType().GetProperties();
  13. foreach (PropertyInfo pi in propertys)
  14. {
  15. tempName = pi.Name;
  16. // 检查DataTable是否包含此列
  17. if (dt.Columns.Contains(tempName))
  18. {
  19. // 判断此属性是否有Setter
  20. if (!pi.CanWrite) continue;
  21. object value = dr[tempName];
  22. if (value != DBNull.Value)
  23. pi.SetValue(t, value, null);
  24. }
  25. }
  26. ts.Add(t);
  27. }
  28. return ts;
  29. }

反射100W次,大约用时:20350毫秒。

方案3:用Melas提供的反射方案:

  1. public static IList<T> ConvertTo<T>(DataTable table)
  2. {
  3. if (table == null)
  4. {
  5. return null;
  6. }
  7. List<DataRow> rows = new List<DataRow>();
  8. foreach (DataRow row in table.Rows)
  9. {
  10. rows.Add(row);
  11. }
  12. return ConvertTo<T>(rows);
  13. }
  14. public static IList<T> ConvertTo<T>(IList<DataRow> rows)
  15. {
  16. IList<T> list = null;
  17. if (rows != null)
  18. {
  19. list = new List<T>();
  20. foreach (DataRow row in rows)
  21. {
  22. T item = CreateItem<T>(row);
  23. list.Add(item);
  24. }
  25. }
  26. return list;
  27. }
  28. public static T CreateItem<T>(DataRow row)
  29. {
  30. T obj = default(T);
  31. if (row != null)
  32. {
  33. obj = Activator.CreateInstance<T>();
  34. foreach (DataColumn column in row.Table.Columns)
  35. {
  36. object value = row[column.ColumnName];
  37. PropertyInfo prop = obj.GetType().GetProperty(column.ColumnName);
  38. try
  39. {
  40. if (value != DBNull.Value && prop != null)
  41. prop.SetValue(obj, value, null);
  42. }
  43. catch
  44. {
  45. // You can log something here
  46. throw;
  47. }
  48. }
  49. }
  50. return obj;
  51. }

反射100W次,大约用时:20258毫秒。

数据库结构:

表名:Roles
 
序号 列名 数据类型 长度 小数位 标识 主键 允许空 默认值 说明
1 RoleID uniqueidentifier 16 0        
2 RoleName nvarchar 260 0        
3 Description nvarchar 512 0        
4 TaskMask nvarchar 32 0        
5 RoleFlags tinyint 1 0        

原本想修改动软代码生成器的模板来生成改写过的DataRowToModel方法,想改成下面这样:

  1. /// <summary>
  2. /// 得到一个对象实体
  3. /// </summary>
  4. private static Roles DataRowToModel(DataRow row)
  5. {
  6. if (row != null)
  7. {
  8. Roles model = new Roles
  9. {
  10. RoleID = new Guid(row["RoleID"].ToString()),
  11. RoleName = row["RoleName"].ToString(),
  12. Description = row["Description"].ToString(),
  13. TaskMask = row["TaskMask"].ToString(),
  14. RoleFlags = int.Parse(row["RoleFlags"].ToString())
  15. };
  16. return model;
  17. }
  18. return null;
  19. }

后来发现一个很悲剧的事,模板里不包含DataRowToModel方法,我看到了下面这个东西:

目前用到的代码生成,我用CodeSmith生成,下面贴出两个模板,可以直接用,已经测试通过。

实体层:

  1. <%@ CodeTemplate Language="C#" TargetLanguage="C#" Description="Generates a very simple business object." %>
  2. <%@ Property Name="SourceTable" Type="SchemaExplorer.TableSchema" Category="Context" Description="Table that the object is based on." %>
  3. <%@ Property Name="SingleFileMode" Type="System.Boolean" Category="Options" Default="True" Description="Generate content for a complete cs file instead of just a class." %>
  4. <%@ Property Name="ClassNamespace" Type="System.String" Category="Options" Default="BusinessObjects" Description="Namespace your class is in. Only used if SingleFileMode is true!" %>
  5. <%@ Assembly Name="SchemaExplorer" %>
  6. <%@ Assembly Name="System.Data" %>
  7. <%@ Import Namespace="SchemaExplorer" %>
  8. <%@ Import Namespace="System.Data" %>
  9. <%@ Map Name="SqlCSharp" Src="Sql-CSharp" Description="System to C# Type Map" %>
  10. <%@ Map Name="DbDataReader" Src="DbType-DataReaderMethod" Description="DbType to DataReader Method Map" %>
  11. <%@ Map Name="SqlNativeSqlDb" Src="SqlNativeType-SqlDbType" Description="SqlNativeType to SqlDbType Map" %>
  12. <%@ Map Name="DbTypeCSharp" Src="DbType-CSharp" Description="DbType to CSharp Map" %>
  13. <% if(this.SingleFileMode) { %>
  14. using System;
  15.  
  16. namespace <%= this.ClassNamespace %>
  17. {
  18. <% } %>
  19. /// <summary>
  20. /// <%= GetClassName(SourceTable) %>:实体类(属性说明自动提取数据库字段的描述信息)
  21. /// </summary>
  22. [Serializable]
  23. public class <%= GetClassName(SourceTable) %>
  24. {
  25. #region Private Properties
  26. <% foreach (ColumnSchema column in SourceTable.Columns) { %>
  27. <%= GetMemberVariableDeclarationStatement(column) %>
  28. <% } %>
  29. #endregion
  30. #region Public Properties
  31. <% ; i < SourceTable.Columns.Count; i++) { %>
  32. /// <summary>
  33. /// <%=SourceTable.Columns[i].Description %>
  34. /// </summary>
  35. public <%= GetCSharpVariableType(SourceTable.Columns[i]) %> <%= GetPropertyName(SourceTable.Columns[i]) %>
  36. {
  37. get {return <%= GetMemberVariableName(SourceTable.Columns[i]) %>;}
  38. set {<%= GetMemberVariableName(SourceTable.Columns[i]) %> = value;}
  39. }
  40. <% ) Response.Write("\r\n"); %>
  41. <% } %>
  42. #endregion
  43. }
  44. <% if(this.SingleFileMode) { %>
  45. }
  46. <% } %>
  47.  
  48. <script runat="template">
  49. public string GetMemberVariableDeclarationStatement(ColumnSchema column)
  50. {
  51. return GetMemberVariableDeclarationStatement("private", column);
  52. }
  53.  
  54. public string GetMemberVariableDeclarationStatement(string protectionLevel, ColumnSchema column)
  55. {
  56. string statement = protectionLevel + " ";
  57. statement += GetCSharpVariableType(column) + " " + GetMemberVariableName(column);
  58.  
  59. string defaultValue = GetMemberVariableDefaultValue(column);
  60. if (defaultValue != "")
  61. {
  62. statement += " = " + defaultValue;
  63. }
  64.  
  65. statement += ";";
  66.  
  67. return statement;
  68. }
  69.  
  70. public string GetCamelCaseName(string value)
  71. {
  72. , ).ToLower() + value.Substring();
  73. }
  74.  
  75. public string GetMemberVariableName(ColumnSchema column)
  76. {
  77. string propertyName = GetPropertyName(column);
  78. string memberVariableName = "_" + GetCamelCaseName(propertyName);
  79.  
  80. return memberVariableName;
  81. }
  82.  
  83. public string GetPropertyName(ColumnSchema column)
  84. {
  85. string propertyName = column.Name;
  86.  
  87. if (propertyName == column.Table.Name + "Name") return "Name";
  88. if (propertyName == column.Table.Name + "Description") return "Description";
  89.  
  90. , propertyName.Length - );
  91.  
  92. return propertyName;
  93. }
  94.  
  95. public string GetMemberVariableDefaultValue(ColumnSchema column)
  96. {
  97. switch (column.DataType)
  98. {
  99. case DbType.Guid:
  100. {
  101. return "Guid.Empty";
  102. }
  103. case DbType.AnsiString:
  104. case DbType.AnsiStringFixedLength:
  105. case DbType.String:
  106. case DbType.StringFixedLength:
  107. {
  108. return "String.Empty";
  109. }
  110. default:
  111. {
  112. return "";
  113. }
  114. }
  115. }
  116.  
  117. public string GetCSharpVariableType(ColumnSchema column)
  118. {
  119. if (column.Name.EndsWith("TypeCode")) return column.Name;
  120.  
  121. return DbTypeCSharp[column.DataType.ToString()];
  122. }
  123.  
  124. public string GetClassName(TableSchema table)
  125. {
  126. return table.Name;
  127. }
  128.  
  129. public override string GetFileName()
  130. {
  131. return this.GetClassName(this.SourceTable) + ".cs";
  132. }
  133. </script>

数据访问层:

  1. <%@ CodeTemplate Language="C#" TargetLanguage="C#" Description="Generates a very simple business object." %>
  2. <%@ Property Name="SourceTable" Type="SchemaExplorer.TableSchema" Category="Context" Description="Table that the object is based on." %>
  3. <%@ Property Name="SingleFileMode" Type="System.Boolean" Category="Options" Default="True" Description="Generate content for a complete cs file instead of just a class." %>
  4. <%@ Property Name="ClassNamespace" Type="System.String" Category="Options" Default="BusinessObjects" Description="Namespace your class is in. Only used if SingleFileMode is true!" %>
  5. <%@ Assembly Name="SchemaExplorer" %>
  6. <%@ Assembly Name="System.Data" %>
  7. <%@ Import Namespace="SchemaExplorer" %>
  8. <%@ Import Namespace="System.Data" %>
  9. <%@ Map Name="SqlCSharp" Src="Sql-CSharp" Description="System to C# Type Map" %>
  10. <%@ Map Name="DbDataReader" Src="DbType-DataReaderMethod" Description="DbType to DataReader Method Map" %>
  11. <%@ Map Name="SqlNativeSqlDb" Src="SqlNativeType-SqlDbType" Description="SqlNativeType to SqlDbType Map" %>
  12. <%@ Map Name="DbTypeCSharp" Src="DbType-CSharp" Description="DbType to CSharp Map" %>
  13. <% if(this.SingleFileMode) { %>
  14. using System;
  15. using System.Collections.Generic;
  16. using System.Data;
  17. using System.Linq;
  18.  
  19. namespace <%= this.ClassNamespace %>
  20. {
  21. <% } %>
  22. public class <%= GetClassName(SourceTable) %>DAL
  23. {
  24.  
  25. /// <summary>
  26. /// 把DataTable转成一个List集合
  27. /// </summary>
  28. public static List<<%= GetClassName(SourceTable) %>> GetRoleses(DataTable dt)
  29. {
  30. List<<%= GetClassName(SourceTable) %>> list = new List<<%= GetClassName(SourceTable) %>>();
  31. )
  32. list.AddRange(from DataRow dataRow in dt.Rows select DataRowToModel(dataRow));
  33. return list;
  34. }
  35.  
  36. /// <summary>
  37. /// 得到一个对象实体
  38. /// </summary>
  39. private static <%= GetClassName(SourceTable) %> DataRowToModel(DataRow row)
  40. {
  41. if (row != null)
  42. {
  43. <%= GetClassName(SourceTable) %> model = new <%= GetClassName(SourceTable) %>
  44. {
  45. <% ; i < SourceTable.Columns.Count; i++) { %>
  46. <%= GetReaderAssignmentStatement(SourceTable.Columns[i], i,SourceTable.Columns.Count-) %>
  47. <%}%>
  48. };
  49. return model;
  50. }
  51. return null;
  52. }
  53.  
  54. }
  55. <% if(this.SingleFileMode) { %>
  56. }
  57. <% } %>
  58.  
  59. <script runat="template">
  60. public string GetReaderAssignmentStatement(ColumnSchema column, int index,int count)
  61. {
  62. string statement = GetMemberVariableName(column) + " = ";
  63. if (column.Name.EndsWith("TypeCode"))
  64. statement += "(" + column.Name + ")";
  65. statement += GetMemberVariableDefaultValue(column);
  66. if(index<count)
  67. statement+=",";
  68. return statement;
  69. }
  70.  
  71. public string GetMemberVariableName(ColumnSchema column)
  72. {
  73. return GetPropertyName(column);
  74. }
  75.  
  76. public string GetPropertyName(ColumnSchema column)
  77. {
  78. string propertyName = column.Name;
  79.  
  80. if (propertyName == column.Table.Name + "Name") return "Name";
  81. if (propertyName == column.Table.Name + "Description") return "Description";
  82.  
  83. , propertyName.Length - );
  84.  
  85. return propertyName;
  86. }
  87.  
  88. public string GetMemberVariableDefaultValue(ColumnSchema column)
  89. {
  90. switch (column.DataType)
  91. {
  92. case DbType.Guid:
  93. {
  94. return "new Guid(row[\""+column.Name+"\"].ToString())";
  95. }
  96. case DbType.AnsiString:
  97. case DbType.AnsiStringFixedLength:
  98. case DbType.String:
  99. case DbType.StringFixedLength:
  100. {
  101. return "row[\""+column.Name+"\"].ToString()";
  102. }
  103. case DbType.Byte:
  104. return "Byte.Parse(row[\""+column.Name+"\"].ToString())";
  105. case DbType.Int16:
  106. return "Int16.Parse(row[\""+column.Name+"\"].ToString())";
  107. case DbType.Int32:
  108. return "Int32.Parse(row[\""+column.Name+"\"].ToString())";
  109. case DbType.Int64:
  110. return "Int64.Parse(row[\""+column.Name+"\"].ToString())";
  111. default:
  112. {
  113. return "aaaa";
  114. }
  115. }
  116. }
  117.  
  118. public string GetCSharpVariableType(ColumnSchema column)
  119. {
  120. if (column.Name.EndsWith("TypeCode")) return column.Name;
  121.  
  122. return DbTypeCSharp[column.DataType.ToString()];
  123. }
  124.  
  125. public string GetClassName(TableSchema table)
  126. {
  127. return table.Name;
  128. }
  129.  
  130. public override string GetFileName()
  131. {
  132. return this.GetClassName(this.SourceTable) + "DAL.cs";
  133. }
  134. </script>

上面的模板生成的是1楼评论中的代码。

后面经过MVC.Net的提醒,改用构造方法来做,具体做法是:

数据访问层就不需要了,只需要一个实体层模板:

  1. <%@ CodeTemplate Language="C#" TargetLanguage="C#" Description="Generates a very simple business object." %>
  2. <%@ Property Name="SourceTable" Type="SchemaExplorer.TableSchema" Category="Context" Description="Table that the object is based on." %>
  3. <%@ Property Name="SingleFileMode" Type="System.Boolean" Category="Options" Default="True" Description="Generate content for a complete cs file instead of just a class." %>
  4. <%@ Property Name="ClassNamespace" Type="System.String" Category="Options" Default="BusinessObjects" Description="Namespace your class is in. Only used if SingleFileMode is true!" %>
  5. <%@ Assembly Name="SchemaExplorer" %>
  6. <%@ Assembly Name="System.Data" %>
  7. <%@ Import Namespace="SchemaExplorer" %>
  8. <%@ Import Namespace="System.Data" %>
  9. <%@ Map Name="SqlCSharp" Src="Sql-CSharp" Description="System to C# Type Map" %>
  10. <%@ Map Name="DbDataReader" Src="DbType-DataReaderMethod" Description="DbType to DataReader Method Map" %>
  11. <%@ Map Name="SqlNativeSqlDb" Src="SqlNativeType-SqlDbType" Description="SqlNativeType to SqlDbType Map" %>
  12. <%@ Map Name="DbTypeCSharp" Src="DbType-CSharp" Description="DbType to CSharp Map" %>
  13. <% if(this.SingleFileMode) { %>
  14. using System;
  15. using System.Data;
  16.  
  17. namespace <%= this.ClassNamespace %>
  18. {
  19. <% } %>
  20. /// <summary>
  21. /// <%= GetClassName(SourceTable) %>:实体类(属性说明自动提取数据库字段的描述信息)
  22. /// </summary>
  23. [Serializable]
  24. public class <%= GetClassName(SourceTable) %>
  25. {
  26. #region Private Properties
  27. <% foreach (ColumnSchema column in SourceTable.Columns) { %>
  28. <%= GetMemberVariableDeclarationStatement(column) %>
  29. <% } %>
  30. #endregion
  31. #region Public Properties
  32. public <%= GetClassName(SourceTable) %>(DataRow row)
  33. {
  34. <% ; i < SourceTable.Columns.Count; i++) { %>
  35. <%=GetMemberVariableName(SourceTable.Columns[i])%> = <%= GetMemberVariableDefaultValue1(SourceTable.Columns[i])%>;
  36. <%}%>
  37. }
  38. <% ; i < SourceTable.Columns.Count; i++) { %>
  39. /// <summary>
  40. /// <%=SourceTable.Columns[i].Description %>
  41. /// </summary>
  42. public <%= GetCSharpVariableType(SourceTable.Columns[i]) %> <%= GetPropertyName(SourceTable.Columns[i]) %>
  43. {
  44. get {return <%= GetMemberVariableName(SourceTable.Columns[i]) %>;}
  45. set {<%= GetMemberVariableName(SourceTable.Columns[i]) %> = value;}
  46. }
  47. <% ) Response.Write("\r\n"); %>
  48. <% } %>
  49. #endregion
  50. }
  51. <% if(this.SingleFileMode) { %>
  52. }
  53. <% } %>
  54.  
  55. <script runat="template">
  56. public string GetMemberVariableDeclarationStatement(ColumnSchema column)
  57. {
  58. return GetMemberVariableDeclarationStatement("private", column);
  59. }
  60.  
  61. public string GetMemberVariableDeclarationStatement(string protectionLevel, ColumnSchema column)
  62. {
  63. string statement = protectionLevel + " ";
  64. statement += GetCSharpVariableType(column) + " " + GetMemberVariableName(column);
  65. string defaultValue = GetMemberVariableDefaultValue(column);
  66. if (defaultValue != "")
  67. {
  68. statement += " = " + defaultValue;
  69. }
  70. statement += ";";
  71. return statement;
  72. }
  73.  
  74. public string GetCamelCaseName(string value)
  75. {
  76. , ).ToLower() + value.Substring();
  77. }
  78.  
  79. public string GetMemberVariableName(ColumnSchema column)
  80. {
  81. string propertyName = GetPropertyName(column);
  82. string memberVariableName = "_" + GetCamelCaseName(propertyName);
  83. return memberVariableName;
  84. }
  85.  
  86. public string GetPropertyName(ColumnSchema column)
  87. {
  88. string propertyName = column.Name;
  89.  
  90. if (propertyName == column.Table.Name + "Name") return "Name";
  91. if (propertyName == column.Table.Name + "Description") return "Description";
  92.  
  93. , propertyName.Length - );
  94.  
  95. return propertyName;
  96. }
  97.  
  98. public string GetMemberVariableDefaultValue(ColumnSchema column)
  99. {
  100. switch (column.DataType)
  101. {
  102. case DbType.Guid:
  103. {
  104. return "Guid.Empty";
  105. }
  106. case DbType.AnsiString:
  107. case DbType.AnsiStringFixedLength:
  108. case DbType.String:
  109. case DbType.StringFixedLength:
  110. {
  111. return "String.Empty";
  112. }
  113. default:
  114. {
  115. return "";
  116. }
  117. }
  118. }
  119.  
  120. public string GetMemberVariableDefaultValue1(ColumnSchema column)
  121. {
  122. switch (column.DataType)
  123. {
  124. case DbType.Guid:
  125. {
  126. return "new Guid(row[\""+column.Name+"\"].ToString())";
  127. }
  128. case DbType.AnsiString:
  129. case DbType.AnsiStringFixedLength:
  130. case DbType.String:
  131. case DbType.StringFixedLength:
  132. {
  133. return "row[\""+column.Name+"\"].ToString()";
  134. }
  135. case DbType.Byte:
  136. return "Byte.Parse(row[\""+column.Name+"\"].ToString())";
  137. case DbType.Int16:
  138. return "Int16.Parse(row[\""+column.Name+"\"].ToString())";
  139. case DbType.Int32:
  140. return "Int32.Parse(row[\""+column.Name+"\"].ToString())";
  141. case DbType.Int64:
  142. return "Int64.Parse(row[\""+column.Name+"\"].ToString())";
  143. default:
  144. {
  145. return "aaaa";
  146. }
  147. }
  148. }
  149.  
  150. public string GetCSharpVariableType(ColumnSchema column)
  151. {
  152. if (column.Name.EndsWith("TypeCode")) return column.Name;
  153.  
  154. return DbTypeCSharp[column.DataType.ToString()];
  155. }
  156.  
  157. public string GetClassName(TableSchema table)
  158. {
  159. return table.Name;
  160. }
  161.  
  162. public override string GetFileName()
  163. {
  164. return this.GetClassName(this.SourceTable) + ".cs";
  165. }
  166. </script>

生成的代码是:

  1. using System;
  2. using System.Data;
  3.  
  4. namespace TestDbUtilityConsole
  5. {
  6. /// <summary>
  7. /// Roles:实体类(属性说明自动提取数据库字段的描述信息)
  8. /// </summary>
  9. [Serializable]
  10. public class Roles
  11. {
  12. #region Private Properties
  13. private Guid _roleID = Guid.Empty;
  14. private string _roleName = String.Empty;
  15. private string _description = String.Empty;
  16. private string _taskMask = String.Empty;
  17. private byte _roleFlags;
  18. #endregion
  19. #region Public Properties
  20. public Roles(DataRow row)
  21. {
  22. _roleID = new Guid(row["RoleID"].ToString());
  23. _roleName = row["RoleName"].ToString();
  24. _description = row["Description"].ToString();
  25. _taskMask = row["TaskMask"].ToString();
  26. _roleFlags = Byte.Parse(row["RoleFlags"].ToString());
  27. }
  28. /// <summary>
  29. /// 列1
  30. /// </summary>
  31. public Guid RoleID
  32. {
  33. get { return _roleID; }
  34. set { _roleID = value; }
  35. }
  36.  
  37. /// <summary>
  38. /// 列2
  39. /// </summary>
  40. public string RoleName
  41. {
  42. get { return _roleName; }
  43. set { _roleName = value; }
  44. }
  45.  
  46. /// <summary>
  47. /// 列3
  48. /// </summary>
  49. public string Description
  50. {
  51. get { return _description; }
  52. set { _description = value; }
  53. }
  54.  
  55. /// <summary>
  56. /// 列4
  57. /// </summary>
  58. public string TaskMask
  59. {
  60. get { return _taskMask; }
  61. set { _taskMask = value; }
  62. }
  63.  
  64. /// <summary>
  65. /// 列5
  66. /// </summary>
  67. public byte RoleFlags
  68. {
  69. get { return _roleFlags; }
  70. set { _roleFlags = value; }
  71. }
  72. #endregion
  73. }
  74. }

调用方法:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Diagnostics;
  5. using System.Threading.Tasks;
  6. using DbUtility;
  7.  
  8. namespace TestDbUtilityConsole
  9. {
  10. class Program
  11. {
  12. static SqlDbUtility db = new SqlDbUtility("Data Source=(local);Initial Catalog=ReportServer;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False");
  13. static void Main(string[] args)
  14. {
  15. DataTable dt = GetDataTable().Result;
  16. Stopwatch timer = new Stopwatch();
  17. timer.Start();
  18. ; i < ; i++)
  19. {
  20. List<Roles> list = new List<Roles>();
  21. Roles roles = null;
  22. foreach (DataRow dataRow in dt.Rows)
  23. {
  24. roles = new Roles(dataRow);
  25. list.Add(roles);
  26. }
  27. }
  28. timer.Stop();
  29. Console.WriteLine("遍历100W次,共耗时{0}毫秒。", timer.ElapsedMilliseconds);
  30. Console.ReadKey();
  31. }
  32.  
  33. static async Task<DataTable> GetDataTable()
  34. {
  35. DataTable dt = await db.T("select * from Roles").ExecuteDataTableAsync();
  36. return dt;
  37. }
  38. }
  39. }

结果:遍历100W次,共耗时9568毫秒。

DbUtility-关于DataTable转成List的效率问题的更多相关文章

  1. 将list<对象>转换成DataTable,把DataTable转换成参数传入存储过程实现批量插入数据

    领导让在存储过程中批量添加数据,找出效率最高的,我看到后台代码后,发现可以将list<对象>转换成DataTable,把DataTable转换成参数传入存储过程实现批量插入数据,知道还有其 ...

  2. DataTable 转换成 Json的3种方法

    在web开发中,我们可能会有这样的需求,为了便于前台的JS的处理,我们需要将查询出的数据源格式比如:List<T>.DataTable转换为Json格式.特别在使用Extjs框架的时候,A ...

  3. DataTable转换成IList<T>的简单实现

    DataTable的无奈 很多时候,我们需要去操作DataTable.但DataTable的操作,实在是太不方便了.Linq?lambda表达式?统统没有... 特别是对现有结果集做进一步筛选,这样的 ...

  4. asp.net dataTable转换成Json格式

    /// <summary> /// dataTable转换成Json格式 /// </summary> /// <param name="dt"> ...

  5. 将DataTable转换成CSV文件

    DataTable用于在.net项目中,用于缓存数据,DataTable表示内存中数据的一个表.CSV文件最早用在简单的数据库里,由于其格式简单,并具备很强的开放性,所以起初被扫图家用作自己图集的标记 ...

  6. C#:DataTable映射成Model

    这是数据库开发中经常遇到的问题,当然,这可以用现成的ORM框架来解决,但有些时候,如果DataSet/DataTable是第三方接口返回的,ORM就不方便了,还得自己处理. 反射自然必不可少的,另外考 ...

  7. 将DataSet(DataTable)转换成JSON格式(生成JS文件存储)

    public static string CreateJsonParameters(DataTable dt) { /**/ /**/ /**/ /* /*********************** ...

  8. C#将DataTable转换成list的方法

    本文实例讲述了C#将DataTable转换成list及数据分页的方法.分享给大家供大家参考.具体如下: /// <summary>   /// 酒店评论列表-分页  /// </su ...

  9. DataTable转换成List<T>

    很多时候需要将DataTable转换成一组model,直接对model执行操作会更加方便直观. 代码如下: public static class DataTableToModel { public ...

随机推荐

  1. jquery 异步请求Demo【转载】

    $(document).ready(function() { $.ajax({ url : "/AjaxAction/LoginArea.ashx", data : {userna ...

  2. HDU 4604 Deque 最长子序列

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4604 Deque Time Limit: 4000/2000 MS (Java/Others)     ...

  3. Swift optional详解

    学习了一阵swift对于optional类型一直不是很了解,为此特意学习了一下,通过观看斯坦福大学的视频,将他所讲的进行了总结 optional 有两个值 1.not set (未设) 代表这个值没有 ...

  4. 循序渐进DB2(第2版)——DBA系统管理、运维与应用案例

    <循序渐进DB2(第2版)——DBA系统管理.运维与应用案例> 基本信息 作者: 牛新庄    出版社:清华大学出版社 ISBN:9787302323013 上架时间:2013-7-3 出 ...

  5. Android之Notification的多种用法

    我们在用手机的时候,如果来了短信,而我们没有点击查看的话,是不是在手机的最上边的状态栏里有一个短信的小图标提示啊?你是不是也想实现这种功能呢?今天的Notification就是解决这个问题的. 我们也 ...

  6. ubuntu12.04软件中心打开错误和 ubuntu 包管理之“:E: 读错误 - read (5: 输入/输出错误) E: 无法解析或打开软件包的列表或是状态文件。”的解决

    执行ubuntu软讲中心时打不开.老是崩溃,从终端也下载不了软件. 执行包管理的update或者search等等会报错: E: 读错误 - read (5: 输入/输出错误) E: 无法解析或打开软件 ...

  7. C语言判断文件是否存在

      用函数access,头文件是io.h,原型:    int   access(const   char   *filename,   int   amode); amode参数为0时表示检查文件的 ...

  8. [转] splice系列系统调用

    关注splice系列系统调用(包括splice,tee和vmsplice)已经有一段时间了,开始的时候并未能领会splice的意义所在,致使得出了“splice系列系统调用不怎么实用”的错误结论.随着 ...

  9. Android TagFlowLayout完全解析 一款针对Tag的布局(转)

    一.概述 本文之前,先提一下关于上篇博文的100多万访问量请无视,博文被刷,我也很郁闷,本来想把那个文章放到草稿箱,结果放不进去,还把日期弄更新了,实属无奈. ok,开始今天的博文,今天要说的是Tag ...

  10. SQL读取系统时间的语法(转)

    --获取当前日期(如:yyyymmdd) select CONVERT (nvarchar(12),GETDATE(),112) --获取当前日期(如:yyyymmdd hh:MM:ss)select ...