Advertisement
priore

DataReader AsEnumerable (LINQ) with fields name

Jul 14th, 2012
1,309
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.10 KB | None | 0 0
  1. // create a static class
  2. public static class DataReaderExtension
  3. {
  4.     public static IEnumerable<Dictionary<string, object>> AsEnumerable(this System.Data.IDataReader source)
  5.     {
  6.         if (source == null)
  7.             throw new ArgumentNullException("source");
  8.  
  9.         while (source.Read())
  10.         {
  11.             Dictionary<string, object> row = new Dictionary<string, object>();
  12.             for (int i = 0; i < source.FieldCount; i++)
  13.             {
  14.                 object value = source.GetValue(i);
  15.         // return an empty string for dbnull value of field type string
  16.                 if (source.GetFieldType(i) == typeof(string) && source.IsDBNull(i))
  17.                     value = string.Empty;
  18.                 row.Add(source.GetName(i), value);
  19.             }
  20.             yield return row;
  21.         }
  22.     }
  23. }
  24.  
  25. // suppose you have a class named MYBooks with properties names ID (int) and TITLE (string)
  26. // and the datareader contains more records with two fileds named ID_BOOK and TITLE
  27.  
  28. myDataReader.AsEnumerable().Select(i => new MYBooks()
  29. {
  30.     ID = (int)i["ID_BOOK"],
  31.     TITLE = (string)i["TITLE"]
  32. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement