tags:

views:

32

answers:

1

I am writing a unit test for a method which fills an object from a datatable. In one specific unit test, I want to check how the object will be filled if the datarow has a null value in it. If I assign a DBNull.value to the datarow, I get an exception while running the test.

I have posted the Subject under test below -

return dt.AsEnumerable().Select(
   row => new ChannelManager{ ChannelId = row.Field<int>("EventId") })
   .ToList();

Test is -

DataSet ds = new DataSet();
DataTable dt1 = new DataTable();
dt1.Columns.Add("EventId", typeof(int));
DataRow dr1 = dt1.NewRow();
dr1["EventId"] = DBNull.value;
dt1.Rows.Add(dr1);
ds.Tables.Add(dt1);
if(!test.ChannelId.HasValue)
           Assert.True(true);

But I get an exception saying Cannot cast DBNull.Value to type 'System.Int'

A: 

When you're reading the value, use a nullable int:

ChannelId = row.Field<int?>("EventId")

DBNull will be automatically converted to null, provided the data type you're requesting is nullable.

Joel Mueller