How to: Call User-Defined Functions Inline

Although you can call user-defined functions inline, functions that are included in a query whose execution is deferred are not executed until the query is executed. For more information, see Introduction to LINQ Queries (C#).

When you call the same function outside a query, LINQ to SQL creates a simple query from the method call expression. The following is the SQL syntax (the parameter @p0 is bound to the constant passed in):

SELECT dbo.ReverseCustName(@p0)  

LINQ to SQL creates the following:

string str = db.ReverseCustName("LINQ to SQL");
Dim str As String = db.ReverseCustName("LINQ to SQL")


In the following LINQ to SQL query, you can see an inline call to the generated user-defined function method ReverseCustName. The function is not executed immediately because query execution is deferred. The SQL built for this query translates to a call to the user-defined function in the database (see the SQL code following the query).

var custQuery =
    from cust in db.Customers
    select new {cust.ContactName, Title =
Dim custQuery = _
    From cust In db.Customers _
    Select cust.ContactName, Title = _
SELECT [t0].[ContactName],  
    dbo.ReverseCustName([t0].[ContactTitle]) AS [Title]  
FROM [Customers] AS [t0]  

See also