Search code examples
c#linqlambdanulllinq-to-entities

String.IsNullOrWhiteSpace in LINQ Expression


I have the following code:

return this.ObjectContext.BranchCostDetails.Where(
    b => b.TarrifId == tariffId && b.Diameter == diameter
        || (b.TarrifId==tariffId && !string.IsNullOrWhiteSpace(b.Diameter))
        || (!b.TarrifId.HasValue) && b.Diameter==diameter);

And I get this error when I try to run the code:

LINQ to Entities does not recognize the method 'Boolean IsNullOrWhiteSpace(System.String)' method, and this method cannot be translated into a store expression."

How can I solve this problem and write code better than this?


Solution

  • You need to replace

    !string.IsNullOrWhiteSpace(b.Diameter)
    

    with

    !(b.Diameter == null || b.Diameter.Trim() == string.Empty)
    

    For Linq to Entities this gets translated into:

    DECLARE @p0 VarChar(1000) = ''
    ...
    WHERE NOT (([t0].[Diameter] IS NULL) OR (LTRIM(RTRIM([t0].[Diameter])) = @p0))
    

    and for Linq to SQL almost but not quite the same

    DECLARE @p0 NVarChar(1000) = ''
    ...
    WHERE NOT (LTRIM(RTRIM([t0].[TypeName])) = @p0)