Datareader is often used for list conversion and model conversion. To be lazy, write lessCodeThere are quite a few. You can also make up the performance by using the cache. I haven't tested it. Which of my colleagues has tested it? You can study it ~~ Paste the compiled code as follows: You can refer to the reference for a bit messy, and the comments will not be written. Everyone on Earth should understand it. Public Static T readertomodel < T > (Idatareader Dr)
{
Try
{
Using (DR)
{
If (Dr. Read ())
{
List < String > List = New List < String > (Dr. fieldcount );
For ( Int I = 0 ; I < Dr. fieldcount; I ++ )
{
List. Add (dr. getname (I). tolower ());
}
T Model = Activator. createinstance < T > ();
Foreach (Propertyinfo pi In Model. GetType (). getproperties (bindingflags. getproperty | Bindingflags. Public | Bindingflags. instance ))
{
If (List. Contains (PI. Name. tolower ()))
{
If ( ! Isnullordbnull (Dr [Pi. Name])
{
Pi. setvalue (model, hacktype (Dr [Pi. name], Pi. propertytype ), Null );
}
}
}
Return Model;
}
}
Return Default (T );
}
Catch (Exception ex)
{
Throw Ex;
}
}
Public Static List < T > Readertolist < T > (Idatareader Dr)
{
Using (DR)
{
List < String > Field = New List < String > (Dr. fieldcount );
For ( Int I = 0 ; I < Dr. fieldcount; I ++ )
{
Field. Add (dr. getname (I). tolower ());
}
List < T > List = New List < T > ();
While (Dr. Read ())
{
T Model = Activator. createinstance < T > ();
Foreach (Propertyinfo Property In Model. GetType (). getproperties (bindingflags. getproperty | Bindingflags. Public | Bindingflags. instance ))
{
If (Field. Contains (property. Name. tolower ()))
{
If ( ! Isnullordbnull (Dr [property. Name])
{
Property. setvalue (model, hacktype (Dr [property. name], property. propertytype ), Null );
}
}
}
List. Add (model );
}
Return List;
}
}
// This class determines whether to convert the null type. Otherwise, an error is returned.
Private Static Object Hacktype ( Object Value, type conversiontype)
{
If (Conversiontype. isgenerictype && Conversiontype. getgenerictypedefinition (). Equals ( Typeof (Nullable <> )))
{
If (Value = Null )
Return Null ;
system. componentmodel. nullableconverter = New system. componentmodel. nullableconverter (conversiontype);
conversiontype = nullableconverter. underlyingtype;
}< br> return convert. changetype (value, conversiontype);
}
Private Static Bool Isnullordbnull ( Object OBJ)
{
Return (OBJ Is Dbnull) | String . Isnullorempty (obj. tostring ())) ? True : False ;
}