Use the Reflect example when converting from dataReader to Entity (resolving the OutOfRangeException error) (downmoon)

Source: Internet
Author: User

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!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.