I have on one side an Access database, where Tbl_Application.id_connexion
is a field with a Guid
type (called 'replication ID' in ms Access terminology).
I am collecting some data from this Tbl_Application table through a DataRow[]
array, dr_Tbl_Application
. The following code reads the first DataRow:
private Guid? mid_connexion = null;
mid_connexion = (Guid)dr_Tbl_Application[0]["id_connexion"]
Everything is ok as long as Tbl_Application.id_connexion
holds a value. In case this field does not hold a value, I will get the following error:
InvalidCastException was unhandled
And these are some things I can see in the immediate window:
? dr_Programme[0]["id_Connexion"]
{}
? dr_Programme[0]["id_Connexion"].GetType()
{Name = "DBNull" FullName = "System.DBNull"}
? dr_Programme[0]["id_Connexion"] is System.DBNull
true
So, to avoid my exception, I guess I'd better test before transfering a unique identifier value from a field in a database to a local variable. This said, I am still bothered by my finding, and I'd like to dig deeper into this issue.
My questions are the following:
- Is there a way to write some basic code to assign a value from a database Guid value to a local Guid object without having to test on
System.DBNull
? - Why should the same instruction, applied on the same object, return different types, depending if the the original fields holds or not a value?
Edit on question 2:
? dr_Programme[0]["id_Connexion"].GetType()
returns System.Guid type when the corresponding field is populated in the original table, while
? dr_Programme[0]["id_Connexion"].GetType()
returns System.DBNull type when the field is null (or not populated) in the original table ...