Null check for where clause in EF

973 views Asked by At

I have a POCO entity that looks like

public class Rebate : IEntity
{
    [Key]
    public int Id { get; set; }

    [ForeignKey("ClassOneId")]
    public virtual ClassOne ClassOne { get; set; }
    public int ClassOneId { get; set; }

    [ForeignKey("ClassTwoCode")]
    public virtual ClassTwo ClassTwo { get; set; }
    public string ClassTwoCode { get; set; }

    public double Rebate { get; set; }

 }

If ClassOne has a value ClassTwo will be null and vice versa, now when I want to run a query checking the name property of each class using linqkit:

var predicate = PredicateBuilder.True<Rebate>();
        if (!string.IsNullOrEmpty(term))
            predicate = predicate.And(x => (x.ClassOne != null ? 
                x.ClassOne.Name.Contains(term) : x.ClassTwo.Name.Contains(term)));

OR

var predicate = PredicateBuilder.False<Rebate>();
        if (!string.IsNullOrEmpty(term))
            predicate = predicate.Or(x => x.ClassOne.Name.Contains(term)).
                Or(x.ClassTwo.Name.Contains(term)));

In both cases I get results where ClassOne matches the term but no results where ClassTwo matches.

My understanding of what is happening is that when ClassOne is null the query is failing and not checking the name property of ClassTwo. What I'm not sure of is how to work around this without running the queries separately and merging the results.

Any one have a better plan?

1

There are 1 answers

0
Ocelot20 On

Does this work?

x => (x.ClassOne != null && x.ClassOne.Name.Contains(term)) ||
     (x.ClassTwo != null && x.ClassTwo.Name.Contains(term))

I know EF handles null checks differently than it would if you were working with in-memory objects because of how SQL needs to handle them. If this doesn't work, try running your query in LINQPad and check what SQL is getting executed and check if it makes sense.