none
Linq and extension methods RRS feed

  • Question

  • I have an extension method defined below

    Code Snippet

    public static bool EndsWithAny(this string value, string[] strings)

    {

    foreach (string s in strings)

    {

    if (value.ToLower().EndsWith(s.Trim().ToLower()))

    return true;

    }

    return false;

    }

     

    And I would like to be able to use this in a linq query like

    Code Snippet

    var q5 = from q in this.DefaultContext.TrialLimiters

    where q.AlertEmail.EndsWithAny(SiteCommon.SystemDomains.Split(','))

    select q;

     

     

    Currently if i run the above query i get the following error

    Method 'Boolean EndsWithAny(System.String, System.String[])' has no supported translation to SQL.

    Which is pretty much what I expected

     

    What my question is, is it possible to somehow define the translation to sql for a given method like the one above and if so, how do you do it?

     

    thanks

    -Kris

    Wednesday, June 18, 2008 10:50 AM

Answers

  • LINQ to SQL does not support translating custom extension methods into TSQL. The complexities of the potential call stack are too great to provide a generalized implementation. As an alternative, you may be able to extend IQueryable and dynamically add to the expresson tree each .EndsWith criteria with an OR operator between them. See the Dynamic Query sample in the C# Samples for VS 2008 (http://code.msdn.microsoft.com/csharpsamples) for some guidance on dynamically creating expression trees.

     

    Jim Wooley

    www.ThinqLinq.com 

     

    Wednesday, June 18, 2008 2:23 PM
    Moderator

All replies

  • LINQ to SQL does not support translating custom extension methods into TSQL. The complexities of the potential call stack are too great to provide a generalized implementation. As an alternative, you may be able to extend IQueryable and dynamically add to the expresson tree each .EndsWith criteria with an OR operator between them. See the Dynamic Query sample in the C# Samples for VS 2008 (http://code.msdn.microsoft.com/csharpsamples) for some guidance on dynamically creating expression trees.

     

    Jim Wooley

    www.ThinqLinq.com 

     

    Wednesday, June 18, 2008 2:23 PM
    Moderator
  • Thanks, I thought it might be put in the too hard basket but i thought i may as well ask anyway Smile

     

    Incidentally I did end up using the dynamic query approach to achieve what i wanted, thanks

    Thursday, June 19, 2008 1:39 PM
  • You can always use the C# 3.0 in a Nutshell PredicateBuilder:

     

    http://www.albahari.com/nutshell/predicatebuilder.html

     

    It can greatly simplify the implementation of any method that involves the use of methods that do have a supported translation to SQL, that evaluate to true or false, and that make use of the And and Or predicates.

    Thursday, June 19, 2008 6:43 PM