title: NpgSQLdataReader GetOrdinal throwing exceptions.. any way around?
body: <p>I built a wrapper around NpgSQL for a bunch of the methods I usually use in my projects' DAL. Two of them, I usually use to fill DTOs straight from a DataReader. Usually in a fill helper method, i'll instanciate the DTO and iterate through the properties mapping the Datareader's data to the corresponding property. The fill method is generated most of the time.</p>
  
  <p>Since i allow many of the properties to be null or use the DTO's default values, I've used a method to check if the dataReader's data is valid for the property before filling in the prperty. So i'll have a IsValidString("fieldname") and a DRGetString("fieldname") methods, like so:</p>
  
  <pre><code>public bool IsValidString(string fieldName)
  {
          if (data.GetOrdinal(fieldName) != -1
              &amp;&amp; !data.IsDBNull(data.GetOrdinal(fieldName)))
              return true;
          else
              return false;
  }
  
  public string DRGetString(string fieldName)
  {
          return data.GetString(data.GetOrdinal(fieldName));
  }
  </code></pre>
  
  <p>My fill method is delagated to whatever method executed the query and looks like:</p>
  
  <pre><code>public static object FillObject(DataParse&lt;PostgreSQLDBDataParse&gt; dataParser)
  {
       TipoFase obj = new TipoFase();   
  
       if (dataParser.IsValidInt32("T_TipoFase"))
          obj.T_TipoFase = dataParser.DRGetInt32("T_TipoFase");
  
       if (dataParser.IsValidString("NM_TipoFase"))
          obj.NM_TipoFase = dataParser.DRGetString("NM_TipoFase");
  
              //...rest of the properties .. this is usually autogenerated by a T4 template
  
       return obj;
  }
  </code></pre>
  
  <p>This was working fine and dandy in NpgSQL pre 2.02. . When the GetOrdinal method was called, and if the field was inexistent in the dataReader, I'd simply get a -1 returned. Easy to return false in IsValidString() and simply skip to the next property. The performace hit from checking inexistent fields was practically neglectable.</p>
  
  <p>Unfortunately, changes to NpgSQL make GetOrdinal throw an exception when the field doesn't exist. I have a simple workaround in which I wrap the code in a try /catch and throw false within the catch. But I can feel the hit in performance, especially when I go in to debug mode. Filling in a long list takes minutes.</p>
  
  <p>Suposedly, NpgSQL has a parameter that can be added to the connection string (Compatability) to support backward compatabilty for this method, but I've never got that to work correctly (I always get an exception because of a mal formed connection string). Anyway, I'm looking for suggestions for better workarounds. Any better way to fill in the object from the datareader or even somehow work around the exception problem?</p>