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 FieldIsNullAsync(SqlDataReader rd, string fieldName) { return await rd.IsDBNullAsync(rd.GetOrdinal(fieldName)); } public static T GetFieldValue(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); } } }