我寫了一個通用數據庫幫助方法,它返回特定實體的記錄。關於優化C#代碼的建議
這裏是我如何做到這一點:
我已經有10個物業也有一個名爲TableName屬性的一類叫做客戶。
有一種方法,只取得Type參數,並返回一個傳入類型的數組。
該方法是如何工作的,通過使用反射得到一個表名,並且激發一個select語句,並且在DataReader的基礎上,它循環遍歷每個colum和傳遞類型的Properties。
因此,問題是假設有100萬條記錄和10個屬性。它循環10(屬性)*(1,000,000條記錄)= 10,000,000次
是否有任何優化的方式來做到這一點,就像使用LINQ對Datareader?
下面是一個代碼
object[] LoadAll(Type type)
{
try
{
object obj = Activator.CreateInstance(type);
SqlConnection conn = new SqlConnection("connection string");
string tableName = type.GetField("TableName").GetValue(obj) as string;
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = string.Format("select * from {0}", tableName);
conn.Open();
List<object> list = new List<object>();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
object obj1 = Activator.CreateInstance(type);
foreach (PropertyInfo propertyInfo in type.GetProperties())
{
obj.GetType().GetProperty(propertyInfo.Name).SetValue(obj1,reader[propertyInfo.Name],null);
}
list.Add(obj1);
}
}
感謝名單
@BreakHead只是好奇,爲什麼你想在你的應用程序中使用這樣的類填充10Lacs記錄?在這裏介紹一些分頁機制是不是更好? – 2011-05-19 11:26:09
這個計算對我來說沒有意義:'10(屬性)*(10條記錄)= 10000000'?從什麼時候開始10次10次,然後100次? – 2011-05-19 11:27:24
@Tony 1 [十萬](http://en.wikipedia.org/wiki/Lakh)= 100,000。 – Rup 2011-05-19 11:34:37