As all of us know as that in database it is tough to handle Null value with with DateTime, String and int datatype.
Once upon time I also face problem with this in Linq with compile query, when I tried to convert null value to Timespan datatype.
Here in below query I assigned all value in variable and each variable with
different datatype as per it need.
int EmployeeId,
string EmployeeName,
System.Timespan StartTime,
System.Timespan EndTime,
string Address1,
string Address2,
string PostalCode,
string City,
string State
var query1=from e in Employees
where e.EmployeeID != null
select new
{
EmployeeId = e.EmployeeID.Value,
EmployeeName = e.EmployeeName,
StartTime = e.StartTime.Value,
EndTime = e.EndTime.Value,
Address1 = e.Address1,
Address2 = e.Address2,
PostalCode = e.PostalCode,
City = e.City, State=e.State
}).FirstOrDefault()
Sometime when StartTime and EndTime field come Null at that moment above one
query give Exception for Null value.
For handling here we use conditional operator that is (?:).
for example : when we write If condition is in this manner.
If()
{ }
else
{ }
for conditional operator (___? __ : __) in same manner we are using it in query expression. By using these how I will display my result and also convert Null value to the Timespan datatype.
Solution :
var strTimeSpan= "10.22 AM";
var query1=from e in Employees
where e.EmployeeID != null
select new
{
EmployeeId = e.EmployeeID.Value,
EmployeeName = e.EmployeeName,
StartTime = (e.StartTime.Value == null ? TimeSpan.Parse(strTimeSpan) :e.StartTime.Value)
EndTime = (e.EndTime .Value == null ? TimeSpan.Parse(strTimeSpan) :e.EndTime .Value),
Address1 = e.Address1,
Address2 = e.Address2,
PostalCode = e.PostalCode,
City = e.City, State=e.State
}).FirstOrDefault()
By the use of TimeSpan.Parse(strTimeSpan) we can convert string to Timespan value
Please give your valuable feedback in comments and for any queries you can right here.
No comments:
Post a Comment