Calling Model-Defined Functions from LINQ Queries

It is possible to use model-defined functions in LINQ, but this requires an extra step to create an appropriate stub method in the CLR.

To call such method from LINQ queries you need to add a common language runtime (CLR) method, mapped to the function defined in the conceptual model, to your application. To map the method, you must apply EdmFunctionAttribute to this method. Note that the NamespaceName and FunctionName parameters of the attribute are the namespace name of the conceptual model and the function name in the conceptual model respectively. Function names in LINQ are case sensitive.

Here is the example of such method.

C#:

[EdmFunction(@"AdventureWorks", @"GetProductRevenue")]
public static global::System.Nullable<decimal> GetProductRevenue(global::System.Nullable<int> productID) {
  throw new NotSupportedException("Direct calls are not supported.");
}

 

Visual Basic:

<EdmFunction("AdventureWorks", "GetProductRevenue")> _
Public Shared Function GetProductRevenue(ByVal productID As Global.System.Nullable(Of Integer)) As Global.System.Nullable(Of Decimal)
    Throw New NotSupportedException("Direct calls are not supported.")
End Function

After this you may use this method in LINQ to Entities queries.

C#:

using (AdventureWorksEntities context = new AdventureWorksEntities()) {
  var products = from p in context.Products
                    where GetProductRevenue(p.ProductID) > 5000
                    select p;
}

 

Visual Basic:

Using context As AdventureWorksEntities = New AdventureWorksEntities
    Dim products As IQueryable(Of Product) = _
        From p In context.Products _
            Where (GetProductRevenue(p.ProductID) > 5000) _
            Select p
End Using

CLR methods don’t need to be directly callable; in the example above the CLR stub throws an exception if called directly. However the existence of the stub allows you to create LINQ expressions that compile correctly, and then at runtime, when used in a LINQ to Entities query, the function call is simply translated by the Entity Framework into a query that runs in the database.

 


Send feedback on this topic

© 2008 - 2024 Devart. All rights reserved.