DbExtensions.cs 992 B

12345678910111213141516171819202122232425262728293031
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. namespace Service
  8. {
  9. public static class DbExtensions
  10. {
  11. // 安全读取 string
  12. public static string SafeGetString(this IDataRecord reader, string fieldName)
  13. => reader[fieldName] as string; // DBNull.Value as string → null
  14. // 安全读取可空值类型(如 int?)
  15. public static T? SafeGetValue<T>(this IDataRecord reader, string fieldName)
  16. where T : struct
  17. {
  18. var val = reader[fieldName];
  19. return (val == DBNull.Value) ? null : (T?)val;
  20. }
  21. public static void AddParameter(this IDbCommand cmd, string name, object value)
  22. {
  23. var param = cmd.CreateParameter();
  24. param.ParameterName = name;
  25. param.Value = value ?? DBNull.Value; // 自动转换
  26. cmd.Parameters.Add(param);
  27. }
  28. }
  29. }