Linq-to-SQL: Ignore null parameters from WHERE clause
        Posted  
        
            by Peter Bridger
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by Peter Bridger
        
        
        
        Published on 2010-03-26T13:50:40Z
        Indexed on 
            2010/03/26
            13:53 UTC
        
        
        Read the original article
        Hit count: 849
        
The query below should return records that either have a matching Id supplied in ownerGroupIds or that match ownerUserId. However is ownerUserId is null, I want this part of the query to be ignored.
    public static int NumberUnderReview(int? ownerUserId, List<int> ownerGroupIds)
    {
        return ( from c in db.Contacts
                 where 
                 c.Active == true 
                 &&
                 c.LastReviewedOn <= DateTime.Now.AddDays(-365) 
                 &&
                 ( // Owned by user
                    !ownerUserId.HasValue || 
                    c.OwnerUserId.Value == ownerUserId.Value
                 )
                 &&
                 ( // Owned by group
                    ownerGroupIds.Count == 0 ||
                    ownerGroupIds.Contains( c.OwnerGroupId.Value )
                 )
                 select c ).Count();
    }
However when a null is passed in for ownerUserId then I get the following error:   Nullable object must have a value.
I get a tingling I may have to use a lambda expression in this instance?
© Stack Overflow or respective owner