检查是否在数据读取器存在的列 [英] Checking to see if a column exists in a data reader

查看:152
本文介绍了检查是否在数据读取器存在的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法,如果一个字段在基于IDataReader的对象存在的W / O只检查一个IndexOutOfRangeException?

Is there a way to see if a field exists in an IDataReader-based object w/o just checking for an IndexOutOfRangeException?

在本质上,我有一个方法这需要一个基于IDataReader的对象,并创建的记录的强类型列表。在1个实例,一个数据读取器有一个字段别人所没有的。我真的不希望重写所有的饲料此方法查询到包括某种形式的这一领域,如果我没有到。我已经能够找出如何做到这一点,到目前为止的唯一方法是将1独特的领域扔进try / catch块,如下图所示。

In essence, I have a method that takes an IDataReader-based object and creates a strongly-typed list of the records. In 1 instance, one data reader has a field that others do not. I don't really want to rewrite all of the queries that feed this method to include some form of this field if I don't have to. The only way I have been able to figure out how to do it so far is to throw the 1 unique field into a try/catch block as shown below.

try
{
    tmp.OptionalField = reader["optionalfield"].ToString();
}
catch (IndexOutOfRangeException ex)
{
    //do nothing
}

有一个更清洁的方式短期添加可选字段到其他查询或复制的加载方法,以便1版使用了可选字段和其他不?

Is there a cleaner way short of adding the "optional field" to the other queries or copying the loading method so 1 version uses the optional field and the other doesn't?

我在2.0框架也。

推荐答案

我最终找到使用 reader.GetName(INT)溶液方法。我创建了下面的方法来涵盖的逻辑。

I ended up finding a solution using the reader.GetName(int) method. I created the below method to encompass the logic.

public bool ColumnExists(IDataReader reader, string columnName)
{
    for (int i = 0; i < reader.FieldCount; i++)
    {
        if (reader.GetName(i) == columnName)
        {
            return true;
        }
    }

    return false;
}

这篇关于检查是否在数据读取器存在的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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