Linq check parameter for null value

Posts   
 
    
fstorz
User
Posts: 3
Joined: 13-Jun-2011
# Posted on: 13-Jan-2012 16:53:07   

Hi there

I'd like to check a value in a linq query i'll pass as a parameter. It can be, that the parameter is null and so i have to check this first. Is this possible in one query?


public bool test(object MyParamObject)
        {
            using (DataAccessAdapter objDb = new DataAccessAdapter())
            {
                LinqMetaData objLinq = new LinqMetaData(objDb);

                var objQuery = from a in objLinq.foo
                               where (MyParamObject != null && a.foo == MyParamObject.foo)
                               select a;
            }
        }

i don't like to do:


if(parameter != null)
                var objQuery = from a in objLinq.foo
                               where a.foo == MyParamObject.foo
                               select a;
else
                var objQuery = from a in objLinq.foo
                               select a;

Thanks a lot for your help!

daelmo avatar
daelmo
Support Team
Posts: 8245
Joined: 28-Nov-2005
# Posted on: 13-Jan-2012 20:00:50   

Hi there. You can't do that, because that is mixing things: MyParamObject != null is a in-memory check and you are putting it into a query that is intended to be expanded to an SQL expression.

What you can do is:

var objQuery = objLinq.Foo;

if(parameter != null)
{
     objQuery = objQuery.Where(a => a.foo == MyParamObject.foo);
}

David Elizondo | LLBLGen Support Team