DCSIMG
DataReader.GetValueOrDefault --> Nice Extension - שלמה גולדברג (הרב דוטנט)

שלמה גולדברג (הרב דוטנט)

מרצה בסלע ויועץ בעולם ה - net.

DataReader.GetValueOrDefault --> Nice Extension

 

 
בעבר כתבתי את הפוסט הזה על Extension ל - DataReader - שיודע לייצר אובייקט מכל שורה ב - reader.
 
כאן אני אראה עוד תוספת נחמדה ל - DataReader.
 
הרבה פעמים אנחנו יכולים לקבל NULL מה - reader, ואנחנו חייבים לבדוק בכל פעם האם זה לא DBNull, בעזרת ה - Extension הבא, הקוד יהיה יותר קריא.
 
(הראשון עבור int והשני עבור string)
 

public static T GetValueOrDefault<T>(this DbDataReader reader, int index, T defaultValue)

{

    if (Convert.IsDBNull(reader[index]))

    {

        return defaultValue;

    }

 

    return (T)reader[index];

}

 

public static T GetValueOrDefault<T>(this DbDataReader reader, string name, T defaultValue)

{

    if (Convert.IsDBNull(reader[name]))

    {

        return defaultValue;

    }

 

    return (T)reader[name];

}

 
 
והשימוש יהיה בצורה הבאה:
 

while (reader.Read())

{

    Category category = new Category();

    category.Id = (int)reader["Id"];

    category.Description = reader.GetValueOrDefault<string>("Description", string.Empty);

 

    list.Add(category);

}

פורסם: Sep 04 2009, 12:14 PM by Shlomo | with 2 comment(s)

תוכן התגובה

Rotem Bloom כתב/ה:

נחמד ושימושי מאוד תודה.

# September 6, 2009 8:52 AM

שלמה גולדברג כתב/ה:

בהמשך לפוסט שהראה איך לקבל ערכי ברירת מחדל עבור עמודות שיכולות להיות NULL בבבסיס הנתונים. שלח לי חבר

# September 6, 2009 2:15 PM
שלח תגובה

(שדה חובה)  

(שדה חובה)  

(אופציונלי)

(שדה חובה) 

Please add 3 and 4 and type the answer here:


Enter the numbers above: