2013-01-24 94 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

相关问题