LINQ to SQL and Null strings, how do I use Contains?

前端 未结 9 908
别那么骄傲
别那么骄傲 2020-12-14 01:23

Here is the query

from a in this._addresses
where a.Street.Contains(street) || a.StreetAdditional.Contains(streetAdditional)
select a).ToList
(
相关标签:
9条回答
  • 2020-12-14 01:56

    You must check first if StreetAdditional is null.

    Try

    where a.Street.Contains(street) || ((a != null) && a.StreetAdditional.Contains(streetAdditional))
    

    This works because && is a shortcut-operator and if a != null yields false, the second expression with the null-value won't be evaluated since the result will be false anyway.

    0 讨论(0)
  • 2020-12-14 01:58

    The most obvious one:

    from a in this._addresses
    where (a.Street != null && a.Street.Contains(street)) || (a.StreetAdditional != null && a.StreetAdditional.Contains(streetAdditional))
    select a).ToList<Address>()
    

    Alternatively you could write an extension method for Contains that accepts a null argument without error. Some might say that it is not so pretty to have such a method, because it looks like a normal method call, but is allowed for null values (thereby setting aside normal null-checking practices).

    0 讨论(0)
  • 2020-12-14 02:00

    I don't think SqlServer gave you a null exception. If it did, then this code is clearly not running though LinqToSql (as you've tagged the question).

    string.Contains would be translated to sql's like, which has no trouble at all with null values.

    0 讨论(0)
  • 2020-12-14 02:05

    I would create an extension method to return an empty sequence if null and then call contains method.

    public static IEnumerable<T> EmptyIfNull<T>(this IEnumerable<T> pSeq)
    {
          return pSeq ?? Enumerable.Empty<T>();
    }
    
    from a in this._addresses
    where a.Street.Contains(street) || 
          a.StreetAdditional.EmptyIfNull().Contains(streetAdditional)
    select a).ToList<Address>()
    
    0 讨论(0)
  • 2020-12-14 02:09

    I'd use the null-coalescing operator...

    (from a in this._addresses
    where (a.Street ?? "").Contains(street) || (a.StreetAdditional ?? "").Contains(streetAdditional)
    select a).ToList<Address>()
    
    0 讨论(0)
  • 2020-12-14 02:13

    You might want to check to make sure the variables street and streetAdditional are not null. I just ran across the same problem and setting them to an empty string seemed to solve my problem.

    street = street ?? "";
    streetAdditional = streetAdditional ?? "";
    from a in this._addresses
    where a.Street.Contains(street) || a.StreetAdditional.Contains(streetAdditional)
    select a).ToList<Address>()
    
    0 讨论(0)
提交回复
热议问题