DbFieldReader.cs 968 B

12345678910111213141516171819202122232425262728293031323334
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace SinoChemCommonUtilities
  7. {
  8. public static class DbFieldReader
  9. {
  10. public static T SafelyReadDbField<T>(object rawFieldValue)
  11. {
  12. if (!DBNull.Value.Equals(rawFieldValue))
  13. {
  14. return (T)Convert.ChangeType(rawFieldValue, typeof(T));
  15. }
  16. else // return default value for each type if db null
  17. {
  18. if (typeof(T) == typeof(string))
  19. {
  20. return (T)Convert.ChangeType("", typeof(string));
  21. }
  22. else if (typeof(T) == typeof(DateTime))
  23. {
  24. return (T)Convert.ChangeType(DateTime.Now, typeof(DateTime));
  25. }
  26. else
  27. {
  28. return default(T);
  29. }
  30. }
  31. }
  32. }
  33. }