Database Reference
In-Depth Information
Solution
Suppose that we have an Employee entity containing the properties FirstName, LastName, and BirthDate, as shown
in Figure
11-3
.
Figure 11-3.
An Employee entity with a few typical properties
We want to create a model-defined function that returns the full name of the employee by combining the
FirstName and LastName columns. We want to create another model-defined function that returns the age of the
employee based on the value in the BirthDate column.
To create and use these functions, do the following:
1.
Right-click the .edmx file in the Solution Explorer, and click Open With
➤
XML Editor. This
will open the .edmx file in the XML Editor.
2.
Insert the code in Listing 11-5 just below the
<Schema>
tag in the conceptual models
section of the .edmx file. This defines the functions in the model.
Listing 11-5.
Code for Model-Defined Functions
<Function Name="FullName" ReturnType="Edm.String">
<Parameter Name="emp" Type="EFRecipesModel.Employee" />
<DefiningExpression>
Trim(emp.FirstName) + " " + Trim(emp.LastName)
</DefiningExpression>
</Function>
<Function Name="Age" ReturnType="Edm.Int32">
<Parameter Name="emp" Type="EFRecipesModel.Employee" />
<DefiningExpression>
Year(CurrentDateTime()) - Year(emp.BirthDate)
</DefiningExpression>
</Function>
3.
Insert into and query the model using code similar to the pattern shown in Listing 11-6.
Listing 11-6.
Inserting into and Querying the Model Invoking the Model-Defined Functions
Using Both eSQL and LINQ
class Program
{
static void Main(string[] args)
{
RunExample();
}