How to: Call Canonical Functions

The EntityFunctions class contains methods that expose canonical functions to use in LINQ to Entities queries. For information about canonical functions, see Canonical Functions.

Note

The AsUnicode and AsNonUnicode methods in the EntityFunctions class do not have canonical function equivalents.

Canonical functions that perform a calculation on a set of values and return a single value (also known as aggregate canonical functions) can be directly invoked. Other canonical functions can only be called as part of a LINQ to Entities query. To call an aggregate function directly, you must pass an ObjectQuery<T> to the function. For more information, see the second example below.

You can call some canonical functions by using common language runtime (CLR) methods in LINQ to Entities queries. For a list of CLR methods that map to canonical functions, see CLR Method to Canonical Function Mapping.

Example 1

The following example uses the AdventureWorks Sales Model. The example executes a LINQ to Entities query that uses the DiffDays method to return all products for which the difference between SellEndDate and SellStartDate is less than 365 days:

using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    var products = from p in AWEntities.Products
                   where EntityFunctions.DiffDays(p.SellEndDate, p.SellStartDate) < 365
                   select p;
    foreach (var product in products)
    {
        Console.WriteLine(product.ProductID);
    }
}
Using AWEntities As New AdventureWorksEntities()
    Dim products = From p In AWEntities.Products _
                   Where EntityFunctions.DiffDays(p.SellEndDate, p.SellStartDate) < 365 _
                   Select p

    For Each product In products
        Console.WriteLine(product.ProductID)
    Next
End Using

Example 2

The following example uses the AdventureWorks Sales Model. The example calls the aggregate StandardDeviation method directly to return the standard deviation of SalesOrderHeader subtotals. Note that an ObjectQuery<T> is passed to the function, which allows it to be called without being part of a LINQ to Entities query.

using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    double? stdDev = EntityFunctions.StandardDeviation(
        from o in AWEntities.SalesOrderHeaders
        select o.SubTotal);

    Console.WriteLine(stdDev);
}
Using AWEntities As New AdventureWorksEntities()
    Dim stdDev As Double? = EntityFunctions.StandardDeviation( _
        From o In AWEntities.SalesOrderHeaders _
        Select o.SubTotal)

    Console.WriteLine(stdDev)
End Using

See also