如何使用泛型将DataReader对象映射到类对象?
例如我需要执行以下操作:
public class Mapper<T> { public static List<T> MapObject(IDataReader dr) { List<T> objects = new List<T>(); while (dr.Read()) { //Mapping goes here... } return objects; } }
IDataReder dataReader = DBUtil.Fetchdata("SELECT * FROM Book"); List<Book> bookList = Mapper<Book>.MapObject(dataReder); foreach (Book b in bookList) { Console.WriteLine(b.ID + "," + b.BookName); }
请注意,Mapper类应该能够映射由T表示的任何类型的对象.
解决方法
我用这个
ValueInjecter
我这样做:
while (dr.Read()) { var o = new User(); o.InjectFrom<DataReaderInjection>(dr); yield return o; }
你会需要这个ValueInjection来工作:
public class DataReaderInjection : KnownSourceValueInjection<IDataReader> { protected override void Inject(IDataReader source,object target,PropertyDescriptorCollection targetProps) { for (var i = 0; i < source.FieldCount; i++) { var activeTarget = targetProps.GetByName(source.GetName(i),true); if (activeTarget == null) continue; var value = source.GetValue(i); if (value == DBNull.Value) continue; activeTarget.SetValue(target,value); } } }