Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nullable Field and SQL Is Null Issue

There are tons of Q&A on stackoverflow related to my question , but I cannot deduce the reasoning of the issue and the solution that works best in this scenario;

So I've a method that allows you to pass a parentID, and based on the value records will be filtered using a LINQ query. The field in the database allows NULL values. Now If I compare fields using == operator in the where clause, the sql emitted is wrong (it doesn't uses IS NULL for the comparison), and hence query yields 0 results. I solved this using Object.Equals() method. That worked, but now I get an exception on passing a NON NULL value, an integer

Unable to create a constant value of type 'System.Object'. Only primitive types or enumeration types are supported in this context.

So I wrote a simple method

using (TestEntities context = new Entities())
{
    return from c in context.ItemMappings
           where c.ParentID.Equals(parentID)
           select new ItemDTO
           {
               ItemID = c.Item.ItemID,
               ItemName = c.Item.ItemName,
               ItemType = new ItemTypeDTO
               {
                   TypeID = c.Item.Type.TypeID,
                   TypeName =c.Item.Type.TypeName
               };
}
like image 326
Kunal Avatar asked Mar 25 '13 15:03

Kunal


2 Answers

Yes your problem would also occur if it's SQL. You have to handle null explicitly, and this should work:

Where (parentID == null && c.ParentID == null) || (parentID == c.ParentID)

This assumes that you want a null to match. If you want null to return all the results unfiltered, instead do:

Where (parentID == null) || (parentID == c.ParentID)

I've had trouble with this even sometimes, and found the way LINQ would translate correctly all the time was to do:

Where (parentID == null) || (parentID != null && parentID == c.ParentID)

This is because even in SQL, if you do where ParentID = @ParentID, a null match returns no results, and you have to use ISNULL to escape it to blank.

like image 90
Brian Mains Avatar answered Oct 12 '22 00:10

Brian Mains


To allow nullable You can also try Like this

  GSectionID = emp.SectionID ?? Guid.Empty,
like image 26
Mohammad Atiour Islam Avatar answered Oct 11 '22 22:10

Mohammad Atiour Islam