在生成代码时经常需要从DataReader转化为Entity
比如
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
当Reader只想取两三个字段(少于Entity的属性个数)时,如果不用try catch就会出错:
OutOfRangeException
再加上(reader[ " P_ID " ]!=null), 也仍然出错。
于是想到用Reflect
得方法如下
#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!
助人等于自助! 3w@live.cn
1116



被折叠的 条评论
为什么被折叠?



