Share via


How to: Use Scalar-Valued User-Defined Functions (LINQ to SQL)

You can map a client method defined on a class to a user-defined function by using the FunctionAttribute attribute. Note that the body of the method constructs an expression that captures the intent of the method call, and passes that expression to the DataContext for translation and execution.

Note

Direct execution occurs only if the function is called outside a query. For more information, see How to: Call User-Defined Functions Inline (LINQ to SQL).

Example

The following SQL code presents a scalar-valued user-defined function ReverseCustName().

CREATE FUNCTION ReverseCustName(@string varchar(100))
RETURNS varchar(100)
AS
BEGIN
    DECLARE @custName varchar(100)
    -- Implementation left as exercise for users.
    RETURN @custName
END

You would map a client method such as the following for this code:

<FunctionAttribute(Name:="dbo.ReverseCustName", _
IsComposable:=True)> _
Public Function ReverseCustName(<Parameter(Name:="string", _
DbType:="VarChar(100)")> ByVal [string] As String) As _
<Parameter(DbType:="VarChar(100)")> String 
    Return CType(Me.ExecuteMethodCall(Me, _
        CType(MethodInfo.GetCurrentMethod, MethodInfo), _
        [string]).ReturnValue, String)
End Function
[Function(Name = "dbo.ReverseCustName", IsComposable = true)]
[return: Parameter(DbType = "VarChar(100)")]
public string ReverseCustName([Parameter(Name = "string",
    DbType = "VarChar(100)")] string @string)
{
    return ((string)(this.ExecuteMethodCall(this,
        ((MethodInfo)(MethodInfo.GetCurrentMethod())),
        @string).ReturnValue));
}

See Also

Other Resources

User-Defined Functions (LINQ to SQL)