1

I Have a method to get all Ticket with filtering by FromDate . my code like this :

public List<Model.Ticket> SelectList(DateTime? fromDate = null)
{
    db.Tickets.Where(row=> (!fromDate.HasValue || (fromDate.HasValue ? (row.Date.Date >= fromDate.Value.Date) : false));
}

but when pass null It returns an exception :

Nullable object must have a value.

what's wrong?

Uthman Rahimi
  • 708
  • 5
  • 22
  • when debug it , fromDate is `null` – Uthman Rahimi Jun 13 '16 at 06:29
  • 1
    This is not a good duplicate of the "what is a null reference exception" because if you look at the expression the OP has already handled the case where `fromDate == null`, yet clearly this crashes. So this is not "you need to find the part that is null", this is more "why does Entity Framework (or Linq2Sql) behave like this. – Lasse V. Karlsen Jun 13 '16 at 07:32
  • 1
    Is this LINQ to EF, LINQ to SQL or LINQ to something else? (If something else, what?) It matters, because the different LINQ providers might handle the expression tree generated by your where clause differently. Also, are there any other nullable instances involved here - could `db` or `row.Date` be `null`? – Tomas Aschan Jun 13 '16 at 07:50
  • @TomasLycken its Linq to SQL , and `row.Date` is `not null` – Uthman Rahimi Jun 13 '16 at 08:19
  • As Nithila Shanmugananthan notes in their answer, the syntax above is still incomplete; I guess you're missing `row => ` at the beginning of the argument to `.Where(...)`...? Could you update the question to list the exact code you're using? (copy using ctrl-c, ctrl-v, not by re-writing it here!) – Tomas Aschan Jun 13 '16 at 10:13
  • @TomasLycken yes , updated – Uthman Rahimi Jun 13 '16 at 10:26
  • @Have you run this code using the debugger? What do you see then? – Tomas Aschan Jun 13 '16 at 13:38

3 Answers3

2

You need to get all Ticket with filtering by FromDate, But in your where condition will only return true or false acording to the formdate you are passing as a parameter.But where condition expect a logic to filter data from the table acording to.You have to modify your where condition as

where(ticket=>ticket.formDate--here what ever the condition you need to apply)

NB: For your lambda expression( db.Tickets.Where(!fromDate.HasValue || (fromDate.HasValue ? (row.Date.Date >= fromDate.Value.Date) : false)) ) the db query will be

 select * from Tickets where true/false--acording to the output 

this won't work

0

Maybe in your object declaration you have to initialize it

David
  • 614
  • 5
  • 20
0

Null to be initialized by using new keyword. As directly assigning null to certain object doesn't carry desired contents. Debugging still shows value to null but it can't be instantiated likewise.

maliks
  • 1,102
  • 3
  • 18
  • 42