How to: Define Custom Functions in the Conceptual Model

[This page is specific to the latest version of the Entity Framework. The latest version is available as the 'Entity Framework' NuGet package. For more information, see Entity Framework Releases and Versioning.]

You can define a custom function in the conceptual model by adding a Function element that contains a DefiningExpression element to the conceptual schema definition language (CSDL) of an .edmx file. You can define any Entity SQL statement, including parameterized statements, in a CommandText element.

For more information, see DefiningExpression (CSDL) and User-Defined Functions (Entity SQL).

Defining a Custom Function in the Conceptual Model

The following procedure assumes that you have an .edmx file open in the XML Editor in Visual Studio. The procedure provides a high-level outline of adding a custom function in the storage model. The example that follows provides more detail about steps in the procedure.

To define a custom function in the conceptual model

  1. Add a Function element to the Schema element in the Conceptual Model Content section of the .edmx file.

    You must specify a return type for the function using the ReturnType attribute.

    For more information, see Function Element (SSDL) , Schema Element (SSDL), and ReturnType (CSDL).

  2. For each parameter that the function accepts, add a Parameter element to the Function element.

    Function parameters are not denoted by a prefix such as @. They are referenced directly by name in the Entity SQL expression that defines the function. Choose parameter names that are not the same as other identifiers that you need to use in the Entity SQL expression.

    For more information, see Parameter Element (CSDL).

  3. Add a DefiningExpression element to the new Function element.

  4. Define an Entity SQL statement in the DefiningExpression element.

  5. Save and close the .edmx file.


The following is an example of a Function element, which you can add to the Schema element in the Conceptual Model Content section of an .edmx file to define a custom function.

<Function Name="YearsSince" ReturnType="Edm.Int32">
  <Parameter Name="date" Type="Edm.DateTime" />
    Year(CurrentDateTime()) - Year(date)

After a function has been defined in the conceptual model, it can be called from within Entity SQL queries in your application. For information about calling the function from LINQ to Entities queries, see How to: Call Functions Defined in the Conceptual Model.

See Also

Build Date: