C#.NET IDataReader擴充 ToList/Get

來源:互聯網
上載者:User

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Data;
using System.Data.Common;
using System.Web.Script.Serialization;
using System.IO;
using System.Security.Cryptography;

namespace Pub.Class {
public static class IDataReaderExtensions {

public static List<TResult> ToList<TResult>(this IDataReader dr) where TResult : class,new() {
List<TResult> list= new List<TResult>();
if (dr == null) return list;
int len = dr.FieldCount;

while (dr.Read()) {
TResult info = new TResult();
for (int j = 0; j < len; j++) {
if (dr[j] == null || string.IsNullOrEmpty(dr[j].ToString())) continue;
System.Reflection.PropertyInfo pi = info.GetType().GetProperty(dr.GetName(j).Trim());
pi.SetValue(info, dr[j], null);
}
list.Add(info);
}
dr.Close(); dr.Dispose(); dr = null;
return list;
}

public static T Get<T>(this IDataReader reader, string field) {
return reader.Get<T>(field, default(T));
}
public static T Get<T>(this IDataReader reader, string field, T defaultValue) {
var value = reader[field];
if(value == DBNull.Value) return defaultValue;
return value.ConvertTo<T>(defaultValue);
}

}
}

 

調用執行個體:

        public virtual IList<EC_Type> SelectListByAll(string order, string fieldList, bool useCache) {
string cacheKey = string.Format("EC_TypeCache_SelectListByAll_{0}_{1}", order, fieldList); IList<EC_Type> list = null;
if (useCache) {
list = (IList<EC_Type>)Cache2.Get(cacheKey);
if (list != null) return list;
}

DbParameter[] dbParams = {
Data.MakeInParam("@Fields", (DbType)SqlDbType.VarChar, 1000, fieldList),
Data.MakeInParam("@Order", (DbType)SqlDbType.VarChar, 100, order),
};
list = Data.GetDbDataReader("EC_Type_SelectListByAll", dbParams).ToList<EC_Type>();
if (useCache) Cache2.Insert(cacheKey, list, cacheSeconds);
return list;
}

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.