从dataReader到Entity转化时利用Reflect示例(解决OutOfRangeException错误)(downmoon)

在生成代码时经常需要从DataReader转化为Entity

比如

<!-- <br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware)<br /> http://www.CodeHighlighter.com/<br /> <br /> --> #region Product
internal static Downmoon.Product.Framework.Components.ProductLoadSingleProduct(IDataReaderreader)
{Downmoon.Product.Framework.Components.Productm_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

当Reader只想取两三个字段(少于Entity的属性个数)时,如果不用try catch就会出错:

OutOfRangeException

再加上(reader[ " P_ID " ]!=null), 也仍然出错。

于是想到用Reflect

得方法如下

<!-- <br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware)<br /> http://www.CodeHighlighter.com/<br /> <br /> --> UsingSystem.Reflection
#region Product
internal static Downmoon.Product.Framework.Components.ProductLoadSingleProduct(IDataReaderreader)
{
Downmoon.Product.Framework.Components.Productm_Product
= new Downmoon.Product.Framework.Components.Product();
Typetype
= 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 (MissingMemberExceptionexception){System.Diagnostics.Debug.WriteLine(exception.Message);}
}
}
return m_Product;
}
#endregion

OK!

助人等于自助! [email protected]

你可能感兴趣的:(exception)