Click here to Skip to main content
15,890,512 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
class tblEmpMaster: this table class is generated from entity framework, in db the column Resignation_Date is nullable.

public class Employee{ public DateTime? Resignation_Date { get; set; }}


public Nullable<System.DateTime> Resignation_Date { get; set; }

emp.Resignation_Date = (DateTime)tbl.Resignation_Date;/// Getting error here


How do I handle when in db column Resignation_Date is having null value?

What I have tried:

I am new to this concept, pls help
Posted
Updated 5-Dec-20 1:18am
v2

It depends what you want to do when the date is null. You can check if it is null via

C#
Resignation_Date.HasValue


So you can do something like

C#
if (tbl.Resignation_Date.HasValue)
{
    emp.Resignation_Date = (DateTime)tbl.Resignation_Date;
}


but if emp.Resignation_Date isn't nullable you'll need to decide what value to give it when there is null, you could maybe use DateTime.MinValue.

Or if emp.Resignation_Date is also nullable then

C#
emp.Resignation_Date = tbl.Resignation_Date;
 
Share this answer
 
Adding to F-ES Sitecore's answer, you could look into the GetValueOrDefault method.
C#
emp.Resignation_Date = tbl.Resignation_Date.GetValueOrDefault(); // Default is MinDate.
emp.Resignation_Date = tbl.Resignation_Date.GetValueOrDefault(DateTime.Today); // Default is today.
Basically, you'll just have to decide what you want to do when the database returns null, or in other words, not a date.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900