I have exception:
The null value cannot be assigned to a member with type System.DateTime which is a non-nullable value type.
Source Error:
var bd = (from d in baza.hpurs where d.userID == userID && d.date !=null select d.date).Max();
My method:
public ActionResult Add_hours(int userID)
{
var dat = DateTime.Today;
var bd = (from d in baza.hours where d.userID == userID && d.date !=null select d.date).Max();
if (bd != dat)
{
return View();
}
else
{
var dd = (from d in baza.hours where d.userID == userID && d.date == dat select d.hoursID).Single();
return RedirectToAction("hours_is", "Employer", new { HoursID = dd });
}
}
It works good, but only when I have 1 or more data in hours table for concrete user.
This error is when I want add hours to table where concrete user hasn’t added any hours.
I haven’t any idea how fix it…
This is one of the points where LINQ to SQL is a leaky abstraction. The semantics of the
Max()function in C# is to throw anInvalidOperationExceptionif there are no elements in the sequence. The semantics of SQL’sMAX()function is to returnNULL. The C# code compiles as if the C# semantics are followed, but the code is never executed as C# code. It is translated into SQL where the SQL semantics rules.To handle this, you need to decide what you want when there are no matching elements. If you want a
nullvalue, explicitly declare a nullable variable and introduce an extra cast toDateTime?to tell LINQ to SQL thatnullmight be returned.