use*_*312 10 c# mapping ado.net automapping
如何使用泛型将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;
}
}
Run Code Online (Sandbox Code Playgroud)
后来我需要调用这个类方法,如下所示:
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);
}
Run Code Online (Sandbox Code Playgroud)
注意,Mapper - 类应该能够映射由T表示的任何类型的对象.
我为此使用ValueInjecter
我正在这样做:
while (dr.Read())
{
var o = new User();
o.InjectFrom<DataReaderInjection>(dr);
yield return o;
}
Run Code Online (Sandbox Code Playgroud)
你需要这个 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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9464 次 |
| 最近记录: |