如何使用LINQ时,最好清理一个SqlDataReader [英] How to best clean up a SQLDataReader when using linq

查看:231
本文介绍了如何使用LINQ时,最好清理一个SqlDataReader的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个返回数据读取器的方法。通常我会用一个围绕数据读取器,这样后,我通过它遍历它被很好地处理包裹。的问题是,我已选择消耗使用LINQ数据读取器,这意味着,在延迟执行导致读者获得初设置。是否有一个合适的模式来消费,而无需建立一个完整的集合使用LINQ的数据读取器处理它的内容是什么?



 使用(System.Data.SqlClient.SqlDataReader读卡器= CallStoredProcedure())
{
返回reader.Cast< System.Data.Common.DbDataRecord方式>()选择(REC = gt;新建ObjectModel.CollectorSummaryItem ()
{
CollectorID =(int)的REC [0],
名称= rec.IsDBNull(1)空:rec.GetString(1),
=信息REC .IsDBNull(2)空:rec.GetString(2)
});
}


解决方案

您需要实际读取在使用块内的读者:

 使用(System.Data.SqlClient.SqlDataReader读卡器= CallStoredProcedure())
{
,而(reader.Read())
{
收益回报新ObjectModel.CollectorSummaryItem()
{
CollectorID =(int)的阅读器[0],
产品名称= reader.IsDBNull(1)?空:reader.GetString(1),
信息= reader.IsDBNull(2)?空:reader.GetString(2)
}
}
}

这将评估与你有什么之前相同或一致的返回类型代码,但不关闭读者直到EM>在的大功告成从中读<。


I have a method that returns a data reader. Normally I would wrap a using around the data reader so that it gets disposed nicely after I iterate through it. THe problem is that I've chosen to consume the data reader using Linq, which means that the defered execution causes the reader to get disposed early. Is there a proper pattern to consume and dispose of the data reader using Linq without having to built a complete collection of it's contents?

using (System.Data.SqlClient.SqlDataReader reader = CallStoredProcedure())
{
    return reader.Cast<System.Data.Common.DbDataRecord>().Select(rec => new ObjectModel.CollectorSummaryItem()
    {
        CollectorID = (int)rec[0],
        Name = rec.IsDBNull(1) ? null : rec.GetString(1),
        Information = rec.IsDBNull(2) ? null : rec.GetString(2)
    });
}

解决方案

You need to actually read from the reader inside the using block:

using (System.Data.SqlClient.SqlDataReader reader = CallStoredProcedure())
{
    while (reader.Read())
    {
        yield return new ObjectModel.CollectorSummaryItem()
        {
            CollectorID = (int)reader[0],
            Name = reader.IsDBNull(1) ? null : reader.GetString(1),
            Information = reader.IsDBNull(2) ? null : reader.GetString(2)
        }
    }
}

This will evaluate to code with the same or consistent return type with what you had before, but doesn't close the reader until after you're done reading from it.

这篇关于如何使用LINQ时,最好清理一个SqlDataReader的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆