C# 检测 IDataReader 是否为空的最佳方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51113/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 10:03:47  来源:igfitidea点击:

What's the best way to detect if an IDataReader is empty?

提问by JC Grubbs

It seems like IDataReader.Read() is always true at least one time (If I'm wrong about this let me know.) So how do you tell if it has no records without just wrapping it in a try/catch?

似乎 IDataReader.Read() 至少有一次总是正确的(如果我错了,请告诉我。)那么,如果不将它包装在 try/catch 中,如何判断它是否没有记录?

回答by Ben Scheirman

if(dr.Read())
{
   //do stuff
}
else
{
 //it's empty
}

usually you'll do this though:

通常你会这样做:

while(dr.Read())
{
}

回答by JamesSugrue

Yes, if you want to use the interface then Read until false is the only way to test. If you are looking for a generic IDataReaderimplementation, you could try DbDataReaderand use the HasRowsproperty.

是的,如果您想使用该接口,那么 Read until false 是唯一的测试方法。如果您正在寻找通用IDataReader实现,您可以尝试DbDataReader使用该HasRows属性。

回答by Stefan Steiger

You can just cast System.Data.IDataReaderto System.Data.Common.DbDataReader

你可以投射System.Data.IDataReaderSystem.Data.Common.DbDataReader

using (System.Data.IDataReader IReader = ICommand.ExecuteReader())
{
    if (((System.Data.Common.DbDataReader)IReader).HasRows)
    {
        //do stuff
    }
} // End Using IReader 

It's pure evil, but it (usually) works ;)

这是纯粹的邪恶,但它(通常)有效;)

(assuming your instance of IDataReaderis implemented by a custom ADO.NET provider, and not some custom silly class of yours which just implements IDataReaderinstead of deriving from DbDataReader[which implements IDataReader]).

(假设您的实例IDataReader是由自定义 ADO.NET 提供程序实现的,而不是您的一些自定义愚蠢类,它只是实现IDataReader而不是从DbDataReader[which 实现IDataReader]派生)。

回答by SimonGates

Just stumbled across this problem and came up with this...

刚刚偶然发现了这个问题并想出了这个......

bool isBeforeEoF;

do
{
    isBeforeEoF = reader.Read();

    if (isBeforeEoF)
    {
        yield return new Foo()
        {
            StreamID = (Guid)reader["ID"],
            FileType = (string)reader["Type"],
            Name = (string)reader["Name"],
            RelativePath = (string)reader["RelativePath"]
        };         
    }

} while (isBeforeEoF);