LINQ Equivalent to User Defined Function RRS feed

  • Question

  • Is there a way to write a User Defined Function in C# that can be used in a LINQ query.  Suppose I want a function that returns the full name with first, middle,  and last names as inputs.  How can I use FullName (f, m, l) in a LINQ query.

    Monday, March 23, 2009 11:38 PM


  • You cannot write a C# function that can be translated into SQL when your query executes.  You can, however, write a SQL user defined function in the database and map it by writing a method on your specialized DataContext, and then use that method in your query.

    public partial class MyDataContext
       public string MyUDF(int x)
           return (string)this.ExecuteMethodCall(this, (MethodInfo)MethodInfo.GetCurrentMethod(), x).ReturnValue

    var query = from x in mydb.Xoos
                       where mydb.MyUDF(x.Flurp) == "hot"
                       select x;

    which will translate to SQL like this

    SELECT t0.Yaya, t0.Flurp, t0.Noof
    FROM Xoos AS t0
    WHERE MyUDF(t0.Flurp) = @p0

    Wayward LINQ Lacky
    Tuesday, March 24, 2009 1:14 AM