Language: C#
DataFieldMappingConsoleSample.IDataReaderEx.cs
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; } } } }
Tags:
Report Abuse
Subscribe
Discuss
News
About
New Snippet
Recent Snippets
My Snippets
Favorites
Web Code
Search
Copy
Line#