Database Reference
In-Depth Information
To create a model-defined function that takes an instance of the Category entity and returns the average unit
price for all of the products in the given category, do the following:
1.
Right-click the .edmx file in the Solution Explorer, and select Open With XML Editor.
2.
Insert the code in Listing 11-1 just below the <Schema> tag in the conceptual models
section of the .edmx file. This defines the function in the model.
Listing 11-1. Definition of the AverageUnitPrice() Function in the Model
<Function Name="AverageUnitPrice" ReturnType="Edm.Decimal">
<Parameter Name="category" Type="EFRecipesModel.Category" />
<DefiningExpression>
ANYELEMENT(Select VALUE Avg(p.UnitPrice)
from EFRecipesEntities.Products as p where p.Category == category
)
</DefiningExpression>
</Function>
3.
Insert into and query the model using code similar to the pattern shown in Listing 11-2.
Listing 11-2. Inserting into and Querying the Model Using the Model-Defined Function
AverageUnitPrice()
class Program
{
static void Main(string[] args)
{
RunExample();
}
static void RunExample()
{
using (var context = new EFRecipesEntities())
{
var c1 = new Category { CategoryName = "Backpacking Tents" };
var p1 = new Product
{
ProductName = "Hooligan",
UnitPrice = 89.99M,
Category = c1
};
var p2 = new Product
{
ProductName = "Kraz",
UnitPrice = 99.99M,
Category = c1
};
 
Search WWH ::




Custom Search