Monday, January 18, 2016

GetOrdinal in C# - Why and How?

In our data access methods, we may use Data Tables, Data Sets or Data Readers. One of the fastest and more efficient way is to use Data Readers. It could be Sql, Oledb or even Ingress data reader.

There are many ways that we can pull out the data from Data Readers. Today we discuss the GetOrdinal method which is a recommended method.

Why it is so important? You can read the details from here. This is what MSDN says about it.

GetOrdinal performs a case-sensitive lookup first. If it fails, a second, case-insensitive search occurs (a case-insensitive comparison is done using the database collation). Unexpected results can occur when comparisons are affected by culture-specific casing rules. For example, in Turkish, the following example yields the wrong results because the file system in Turkish does not use linguistic casing rules for the letter 'i' in "file". The method throws an IndexOutOfRangeexception if the zero-based column ordinal is not found.

Lets see how we can implement it. Have a look at the following code sample.

 public List<MyEntity> GetEntityList()  
     {  
       List<MyEntity> MyEntityList = new List<MyEntity>();        
       DataAccessClass dbAccess = new DataAccessClass ();  
       string sProcName = "MyProcName";  
       try  
       {  
         using (SqlDataReader dr = dbAccess.ExecuteReader(sProcName))  
         {   
             int idOrdinal = dr.GetOrdinal("id");  
             int nameOrdinal = dr.GetOrdinal("name");  
             while (dr.Read())  
             {  
               MyEntity me = new MyEntity ();  
               me.id= dr.Getint32(idOrdinal);  
               me.name= dr.GetString(nameOrdinal);  
               MyEntityList .Add(pa);  
             }            
         }  
       }  
       catch (Exception ex)  
       {  
         throw new Exception(ex.Message, ex);  
       }  
       return MyEntityList ;  
     }  

Try it with your own entities and DB Access classes. Compare it with Data Tables and Data Sets and use whenever necessary. Happy Coding :)

No comments:

Post a Comment