When generating code, you often need to convert from DataReader to Entity
For example
Product # region Product
Internal static Downmoon. Product. Framework. Components. Product LoadSingleProduct (IDataReader reader)
{Downmoon. Product. Framework. Components. Product m_Product = new Downmoon. Product. Framework. Components. Product ();
If (reader ["P_ID"]! = DBNull. Value ){
M_Product.P_ID = Convert. ToInt64 (reader ["P_ID"]);
}
If (reader ["P_Name"]! = DBNull. Value ){
M_Product.P_Name = Convert. ToString (reader ["P_Name"]);
}
If (reader ["P_SingleIntro"]! = DBNull. Value ){
M_Product.P_SingleIntro = Convert. ToString (reader ["P_SingleIntro"]);
}
If (reader ["P_Intro"]! = DBNull. Value ){
M_Product.P_Intro = Convert. ToString (reader ["P_Intro"]);
}
/**///////*****************************
Return m_Product;
}
# Endregion
When Reader only wants to retrieve two or three fields (less than the number of Entity attributes), an error occurs if try catch is not required:
OutOfRangeException
Add (reader ["P_ID"]! = Null.
So I thought of using Reflect
The method is as follows:
Using System. Reflection
Product # region Product
Internal static Downmoon. Product. Framework. Components. Product LoadSingleProduct (IDataReader reader)
{
Downmoon. Product. Framework. Components. Product m_Product = new Downmoon. Product. Framework. Components. Product ();
Type type = m_Product.GetType ();
For (int I = 0; I <reader. FieldCount; I ++)
{
If (! Reader. IsDBNull (I ))
{
Try {type. InvokeMember (reader. GetName (I), BindingFlags. Default | BindingFlags. SetProperty, null, m_Product, new object [] {reader. GetValue (I )});}
Catch (MissingMemberException exception) {System. Diagnostics. Debug. WriteLine (exception. Message );}
}
}
Return m_Product;
}
# Endregion
OK!