How to: Define Custom Functions in the Conceptual Model (Entity Framework)
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.
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
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 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).
Add a DefiningExpression element to the new Function element.
Define an Entity SQL statement in the DefiningExpression element.
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. Adding this Function element to the School model provides functionality for determining the number of years since an instructor was hired.
For information about the School model example, see Creating the School Sample Database (Entity Framework Quickstart) and Generating the School .edmx File (Entity Framework Quickstart).
<Function Name="YearsSince" ReturnType="Edm.Int32"> <Parameter Name="date" Type="Edm.DateTime" /> <DefiningExpression> Year(CurrentDateTime()) - Year(date) </DefiningExpression> </Function>
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 Model-Defined Functions in Queries (LINQ to Entities).