如何使用LINQ从SQLReader这样的表中逐行读取数据

时间:2011-06-17 13:15:38

标签: linq-to-sql

有人可以告诉我如何使用Linq替换此代码吗?

使用Microsoft.Practices.EnterpriseLibrary.Data;

Public IDataReader GetRowByRowData()
{
 Database Db = DatabaseFactory.CreateDatabase();
 string sqlString = "SELECT *  FROM TableTest";
 DbCommand DbCmd = PpwDb.GetSqlStringCommand(sqlString);
 Db .ExecuteReader(DbCmd);
}

请使用Linq

帮助从表TableTest获取逐行数据

3 个答案:

答案 0 :(得分:1)

你可以这样做:

   var myQyery=from a in dataContext.Mytable
           select a;

  foreach(var item in myQuery)
{
    //what you like
}

答案 1 :(得分:0)

var records = (from p in context.TableTest
               select p).ToList();

foreach(var record in records) {
  // loop through each record here
}

ToList方法将查询数据库并获取结果集。

答案 2 :(得分:0)

我将表中的主键加载到列表中。根据数据集和主键的大小,加载到列表中不会花费太长时间。加载密钥后,使用带有where子句的FirstOrDefault():

var keys = Db.TableTest.Select(x => x.primaryKey).ToList();

foreach (var k in keys)
{
    var record = (from i in Db.TableTest
             where i.primaryKey == k
             select new
             {
              //Select only the columns you need to conserve memory
                 col1 = i.col1,
                 col2 = i.col2
             }).FirstOrDefault();

    //Process the record
}