0

I have checked couple of post here suggesting how to deal with DBNull vale so I followed the same. Here are my code. But still I am getting the error message

Object can not be cast from DBNull to other types.

What am I missing here?

     public IEnumerable<MyClass> ConvertRowToStd(Datatable table, Datetime dt)
     {
       List<MyClass> targets = new List<MyClass>();
       EntityMapper mapper =  new EntityMapper();

       return(
               from DataRow r in table.Rows
               select new MyClass
               {
                   StartDate = dt.Date,
                   // other mapping goes here
                   EndDate =  row["End_Date"] != DBBull.Value ? Convert.ToDatetime(row["End_Date"]) : (DateTime?)null
                }
             )
       }

Here is MyClass

public class MyClass
{
    public DateTime StartDate {get; set;}
    //
    //
    public DateTime? EndDate {get; set;}

}

user2019
  • 187
  • 1
  • 4
  • 16
  • Which line is the error appearing on? Is it on the StartDate or EndDate? If you use ordinal values rather than named columns you can use built in helper methods such as IsDBNull(int ordinal) and GetDateTime(int ordinal) which might make what you're trying a little cleaner. https://learn.microsoft.com/en-us/dotnet/api/system.data.common.dbdatareader.getdatetime?view=net-6.0 – emagers Apr 06 '22 at 20:31
  • Does this answer your question? [Object cannot be cast from DBNull to other types](https://stackoverflow.com/questions/6098646/object-cannot-be-cast-from-dbnull-to-other-types) – Crowcoder Apr 06 '22 at 20:59
  • @EricMagers its in EndDate. Looking to the MS document you provided. Thank you. – user2019 Apr 07 '22 at 13:53
  • @Crowcoder unfortunately no. I did tried before posting here. – user2019 Apr 07 '22 at 13:53

0 Answers0