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 an InvalidOperationException
if there are no elements in the sequence. The semantics of SQL's MAX()
function is to return NULL
. 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 null
value, explicitly declare a nullable variable and introduce an extra cast to DateTime?
to tell LINQ to SQL that null
might be returned.
DateTime? bd = (from d in baza.hpurs
where d.userID == userID && d.date !=null
select (DateTime?)d.date).Max();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With