Domanda

(LocalVariable) ABC.string (Nome) = (IDataReader) datareader.GetString (0);

questo valore nome proviene dal database .. ciò che accade qui è se questo valore è nullo nome durante la lettura è un'eccezione?

sto facendo manualmente alcuni se la condizione qui. Io non voglio scrivere una condizione manuale per controllare tutte le mie variabili ..

sto facendo qualcosa di simile ora ..

string abc =  (Idatareader)datareader.GetValue(0);
if(abc = null)
    //assiging null
else
    assiging abc value

C'è qualcosa di simile possiamo scrivere metodo di estensione per questo? grazie

È stato utile?

Soluzione

Ecco un paio di metodi di estensione che sarà piacevolmente avvolgere tutte le vostre preoccupazioni in tutto il recupero di valori fortemente tipizzati da un lettore di dati. Se il valore è DBNull verrà restituito il valore di default del tipo. Nel caso di string che è una classe, un null verrà restituito. Se il campo era int, quindi 0 sarebbe stato restituito. Inoltre, se vi aspettate un int?, ad esempio da un campo int nullable, null sarebbe tornato.

Utilizzo specifico per il caso di Kumar:

string abc = datareader.GetValueOrDefault<string>(0);

Utilizzo generale

var name = GetValueOrDefault<string>(reader, "Name");

o

var name = reader.GetValueOrDefault<string>("Name");

o

var name = reader.GetValueOrDefault<string>(0);

estensione

public static class NullSafeGetter
{
   public static T GetValueOrDefault<T>(this IDataRecord row, string fieldName)
   {
       int ordinal = row.GetOrdinal(fieldName);
       return row.GetValueOrDefault<T>(ordinal);
   }

   public static T GetValueOrDefault<T>(this IDataRecord row, int ordinal)
   {
       return (T)(row.IsDBNull(ordinal) ? default(T) : row.GetValue(ordinal));
   }
}

http: // skysanders .net / sottotesto / archive / 2010/03/02 / generic-nullsafe-IDataRecord-campo-getter.aspx

Altri suggerimenti

Simile a @ sky-Sanders risposta, ma meno severi con conversioni:

public static T Get<T>(this IDataRecord row, string fieldName)
{
    int ordinal = row.GetOrdinal(fieldName);
    return row.Get<T>(ordinal);
}

public static T Get<T>(this IDataRecord row, int ordinal)
{
    var value = row.IsDBNull(ordinal) ? default(T) : row.GetValue(ordinal);
    return (T)Convert.ChangeType(value, typeof(T));
}

La mia soluzione è che:

private static T GetValue<T>(object o) {
    if (typeof(DBNull) != o.GetType()) {
        return (T) o;
    }
    return default(T);
}

Quando, Status = GetValue<string>(currentDataRow["status"])

La combinazione di soluzioni migliori e suggerimenti, ecco un C # 6 espressione freccia versione con supporto per GetValue<T> e GetValueOrDefault<T> con i parametri valore opzionale.

public static class DataRecordExtensions {
    /// <summary>
    /// Generically extracts a field value by name from any IDataRecord as specified type. Will throw if DNE.
    /// </summary>
    public static T GetValue<T>(this IDataRecord row, string fieldName)
        => row.GetValue<T>(row.GetOrdinal(fieldName));

    /// <summary>
    /// Generically extracts a field value by ordinal from any IDataRecord as specified type. Will throw if DNE.
    /// </summary>
    public static T GetValue<T>(this IDataRecord row, int ordinal)
        => (T)row.GetValue(ordinal);

    /// <summary>
    /// Generically extracts a field value by name from any IDataRecord as specified type. Will return default generic types value if DNE.
    /// </summary>
    public static T GetValueOrDefault<T>(this IDataRecord row, string fieldName, T defaultValue = default(T))
        => row.GetValueOrDefault<T>(row.GetOrdinal(fieldName), defaultValue);

    /// <summary>
    /// Generically extracts a field value by ordinal from any IDataRecord as specified type. Will return default generic types value if DNE.
    /// </summary>
    public static T GetValueOrDefault<T>(this IDataRecord row, int ordinal, T defaultValue = default(T))
        => (T)(row.IsDBNull(ordinal) ? defaultValue : row.GetValue(ordinal));
}

mi piacerebbe usare qualcosa di simile:

string abc = (IDataReader)datareader.GetValue(0) ?? "Default";
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top