Professional DevExpress ASP.NET Controls contains a sample that uses a helper method I created called SafeRead. SafeRead includes a check for DBNull and null and then converts the field to the correct (or desired) type. One reader asked if it could be modified to work with Guids. I created a simple table with a primary key and a Guid column and used the sample code (in Listing 1); it appears that SafeRead handles Guids fine.
Listing 1: A helper method that reads database fields with a built-in check for null.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
namespace SafeReadTest
{
class Program
{
static void Main(string[] args)
{
string connectionString =
@"Data Source=.\SQLEXPRESS;Initial Catalog=SafeReadTest;Integrated Security=True;Pooling=False";
List<SafeReadTable> list = new List<SafeReadTable>();
using (SqlConnection connection =
new SqlConnection(connectionString))
{
connection.Open();
string SQL = "SELECT * FROM SafeReadTable";
SqlCommand command = new SqlCommand(SQL, connection);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
SafeReadTable o = new SafeReadTable();
o.ID = SafeRead<int>("ID", reader, 0);
o.GuidColumn = SafeRead<Guid>("GuidColumn", reader, Guid.NewGuid());
list.Add(o);
}
}
Array.ForEach<SafeReadTable>(list.ToArray(),
o=>Console.WriteLine(o.GuidColumn));
Console.ReadLine();
}
private static T SafeRead<T>(string fieldname,
SqlDataReader reader, T defaultValue)
{
object o = reader[fieldname];
return o == null || o == System.DBNull.Value ?
defaultValue : (T)Convert.ChangeType(o, typeof(T));
}
}
public class SafeReadTable
{
private int iD;
public int ID
{
get { return iD; }
set { iD = value; }
}
private Guid guidColumn;
public Guid GuidColumn
{
get { return guidColumn; }
set
{
guidColumn = value;
}
}
}
}
A reasonable revision to custom entity classes is to use nullable types {e.g. int?}. This will let you assign null values instead of default values to entity properties.