Click here to Skip to main content
15,884,472 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi,
I am using entity framework in my application. Consider I am having a following table structure
SQL
Employee(
ID uniqueidentifier,
Name varchar(100) not null,
JobId uniqueidentifier null)


I am using the following expression to get the data

C#
Expression<Func<Employee,true>> predicate=p=>p.JobId==JobIdVariable;
**JobIdVariable is nullable Guid. 


So I am using the above expression in Where Clause of Employee object Context.Above solution works fine if jobIdVariable has any data but when it is NULL, then the query returns no rows. When I use SQL profiler, I am getting the following where clause
JobId = NULL, but in this case I have to get JobId IS NULL. So how can I modify my expression to get the Null values from DB.

Thanks for your time
Posted
Updated 17-Nov-14 21:32pm
v2

replace the NULL with 0 in both side of where condition.

something like
SQL
Isnull(JobID,0)=Isnull(jobIdVariable,0).


You would have to convert above expression as per the language requirement.
 
Share this answer
 
v2
Comments
Prasaad SJ 18-Nov-14 3:44am    
Hi Shweta,
Can you describe this in detail? What is Isnull here? I am using C# btw.
Shweta N Mishra 18-Nov-14 3:51am    
Isnull is a function in SQL which replaces Null value to given value, in above example it will replace it to zero. In C# you can use string.IsNullOrEmpty to get same result.
Prasaad SJ 18-Nov-14 4:52am    
Hi Shweta,
I m sorry, I still couldn't get your solution. string.IsNullorEmpty always return a bool and can we use this in expression to compare?? And more over my data type is GUID? (so I can't use .ToString here, it will throw error when the value is null).
After few trial attempts, I could find the solution for this question. If the type is of nullable type, then in expression we have use both Equals and == .

Eg: In my above case in the question, its working correct when
C#
Expression<func><employee,true>> predicate;
if(JobIdVariable==null)
{
    predicate=p=>p.JobId.Equals(null);
   //In this case, the value has to be null and compare has to be Equals else it through some Object related error.
}
else
{
    predicate=p=>p.JobId==JobIdVariable;
//Here, it has to be == comparision else some runtime error is thrown.
}</func>
 
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