CodePaste Logo
New Snippet New Recent Snippets Recent Snippets My Snippets My Snippets My Favorites Favorites Web Code Search Snippets Search
Sign inor Register
Language: csharp

DataFieldMappingConsoleSample.IDataReaderEx.cs

153 Views   
namespace DataFieldMappingConsoleSample { using System; using System.Collections.Generic; using System.Data; using System.Diagnostics; using System.Linq; using System.Reflection; [AttributeUsage(AttributeTargets.Property)] public class DataFieldMappingAttribute : Attribute { public DataFieldMappingAttribute(string fieldName) { this.FieldName = fieldName; } public string FieldName { get; set; } } public static class IDataReaderEx { public static bool TryGetOrdinal(this IDataReader reader, string name, out int ordinal) { try { ordinal = reader.GetOrdinal(name); return true; } catch { ordinal = int.MinValue; return false; } } public static IEnumerable<T> AsEnumerable<T>(this IDataReader reader) where T : new() { int ordinal; var mappings = typeof(T).GetProperties() .Where(pi => pi.GetCustomAttributes(true).Any(attribute => attribute.GetType().FullName == typeof(DataFieldMappingAttribute).FullName)) .Select(pi => new Mapping() { PropertyInfo = pi, DataFieldMapping = (DataFieldMappingAttribute)pi.GetCustomAttributes(true).Where(attribute => attribute.GetType().FullName == typeof(DataFieldMappingAttribute).FullName).First() }); while (reader.Read()) { T t = new T(); mappings.All( item => { if (reader.TryGetOrdinal(item.DataFieldMapping.FieldName, out ordinal)) { item.PropertyInfo.SetValue(t, reader[ordinal], null); } else { Debug.WriteLine(string.Format("DataFieldMappingAttribute '{0}' not found on the reader field collection", item.DataFieldMapping.FieldName), "Warning"); } return true; } ); yield return t; } } private class Mapping { public PropertyInfo PropertyInfo { get; set; } public DataFieldMappingAttribute DataFieldMapping { get; set; } } } }
by Luciano Evaristo Guerche (Gorše)
  December 21, 2011 @ 10:18am
Tags:
Add a comment


Report Abuse
brought to you by:
West Wind Techologies