summaryrefslogtreecommitdiff
path: root/Gestor.Infrastructure/Gestor.Infrastructure.Helpers/SqlDataReaderHelper.cs
diff options
context:
space:
mode:
Diffstat (limited to 'Gestor.Infrastructure/Gestor.Infrastructure.Helpers/SqlDataReaderHelper.cs')
-rw-r--r--Gestor.Infrastructure/Gestor.Infrastructure.Helpers/SqlDataReaderHelper.cs66
1 files changed, 66 insertions, 0 deletions
diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Helpers/SqlDataReaderHelper.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Helpers/SqlDataReaderHelper.cs
new file mode 100644
index 0000000..c4087f8
--- /dev/null
+++ b/Gestor.Infrastructure/Gestor.Infrastructure.Helpers/SqlDataReaderHelper.cs
@@ -0,0 +1,66 @@
+using System;
+using System.Data.Common;
+using System.Data.SqlClient;
+using System.Diagnostics;
+using System.Runtime.CompilerServices;
+using System.Threading.Tasks;
+
+namespace Gestor.Infrastructure.Helpers
+{
+ internal static class SqlDataReaderHelper
+ {
+ public static bool FieldIsNull(this SqlDataReader rd, string fieldName)
+ {
+ return rd.IsDBNull(rd.GetOrdinal(fieldName));
+ }
+
+ public static async Task<bool> FieldIsNullAsync(SqlDataReader rd, string fieldName)
+ {
+ return await rd.IsDBNullAsync(rd.GetOrdinal(fieldName));
+ }
+
+ public static T GetFieldValue<T>(this SqlDataReader rd, string fieldName, bool normalizeNull = true, bool transformField = true)
+ {
+ Type type = rd[fieldName].GetType();
+ Type type1 = typeof(T);
+ if (type == typeof(DBNull))
+ {
+ if (normalizeNull && (!type1.IsGenericType || !(type1.GetGenericTypeDefinition() == typeof(Nullable<>))))
+ {
+ if (type1 == typeof(int) || type1 == typeof(double) || type1 == typeof(decimal) || type1 == typeof(long))
+ {
+ return (T)Convert.ChangeType(0, type1);
+ }
+ if (type1 == typeof(DateTime))
+ {
+ return (T)Convert.ChangeType(DateTime.MinValue, type1);
+ }
+ if (type1 == typeof(bool))
+ {
+ return (T)Convert.ChangeType(false, type1);
+ }
+ }
+ return default(T);
+ }
+ Type underlyingType = Nullable.GetUnderlyingType(type1) ?? type1;
+ if (type == underlyingType)
+ {
+ return (T)rd[fieldName];
+ }
+ if (!transformField)
+ {
+ return (T)rd[fieldName];
+ }
+ object item = rd[fieldName];
+ if (underlyingType.IsEnum)
+ {
+ item = Enum.Parse(underlyingType, item.ToString());
+ }
+ if (type == typeof(string) && underlyingType == typeof(bool))
+ {
+ item = (string)item == "1";
+ }
+ return (T)Convert.ChangeType(item, underlyingType);
+ }
+ }
+} \ No newline at end of file