2013-01-24 91 views
0

我正在使用通用列表來存儲通過查詢數據庫來的數據。我使用實際用於多行的類列表。 但我的問題是我的課有近20多個屬性,大部分時間我只使用其2或3個屬性。 所以我想知道什麼是保持數據來自數據庫的最佳方式。在通用列表中存儲來自數據庫的數據

下面是我的代碼

List<ImageGalleryCollection> tempList = new List<ImageGalleryCollection1>(); 
SqlConnection connection = Dal.GetConnection(); 
SqlParameter[] paramList = new SqlParameter[1]; 
paramList[0] = new SqlParameter("@cityId", cityId); 
SqlDataReader data = Dal.ExecuteReaderSP(SPNames.GetRegCity, paramList, connection); 

while(data.Read()) 
{ 
    ImageGalleryCollection igc = new ImageGalleryCollection1(); 

    igc.cityPhotoGalleryId = Convert.ToInt32(data["cityPhotoGalleryId"]);  
    igc.ImagePath = data["imagePath"].ToString(); 
    tempList.Add(igc);   
} 

data.Close(); 
connection.Close(); 
return tempList; 

在ImageGalleryCollection我有更多的20個物業及以上的,我只使用了兩個properties.I認爲這是非常低效的

回答

0

你能怎麼你的基類的實現?您可以使用最多使用屬性創建另一個類,並在類中使用該類的對象。

+1

在這種情況下,我必須創建多個類 – Vishwajeet

+0

使用OOP原則。 – Kalanamith

0
IEnumerable<ImageGalleryCollection> GetImageGalleryCollection() 
{  

     SqlConnection connection = Dal.GetConnection(); 
     SqlParameter[] paramList = new SqlParameter[1]; 
     paramList[0] = new SqlParameter("@cityId", cityId); 
     SqlDataReader data = Dal.ExecuteReaderSP(SPNames.GetRegCity, paramList,connection); 
     while(data.Read()) 
     { 
      ImageGalleryCollection igc = new ImageGalleryCollection1(); 

      igc.cityPhotoGalleryId = Convert.ToInt32(data["cityPhotoGalleryId"]);  
      igc.ImagePath = data["imagePath"].ToString(); 
      yield return igc; 

     } 
     data.Close(); 
     connection.Close(); 
} 
0

我想建議你寫一個擴展方法爲SqlDataReader,並在linq使用的方法,從讀者的返回的行獲取所需的列。

擴展方法:

public static class DataReaderExtension 
    { 
     public static IEnumerable<Object[]> DataRecord(this System.Data.IDataReader source) 
     { 
      if (source == null) 
       throw new ArgumentNullException("source"); 

      while (source.Read()) 
      { 
       Object[] row = new Object[source.FieldCount]; 
       source.GetValues(row); 
       yield return row; 
      } 
     } 
    } 

在LINQ中使用它:

using (SqlConnection cn = new SqlConnection(connectionString)) 
      { 
       using (SqlCommand cmd = new SqlCommand("Select * from tblUser")) 
       { 
        cmd.CommandType = CommandType.Text; 
        cmd.Connection = cn; 
        cn.Open(); 
        using (SqlDataReader dr = cmd.ExecuteReader()) 
        { 
         var result = (from row in dr.DataRecord() 
             select new 
             { 
              UserId = row[0], 
              UserName = row[1] 
             }).ToList();       
        } 
       } 
      } 

這一結果列表只有必需的屬性選擇,並有助於減少內存消耗不必要的性能。

+0

但我們無法在使用linq時將var結果傳遞給另一頁 – Vishwajeet

相關問題