Database Reference
In-Depth Information
using (var context = new EF6RecipesContext())
{
Console.WriteLine("Members by message count for {0}",
today.ToShortDateString());
var members = context.MembersWithTheMostMessages(today);
foreach (var member in members)
{
Console.WriteLine("Member: {0}", member.Name);
}
}
Following is the output of the code in Listing 10-14:
Members by message count for 5/7/2013
Member: Jill Robertson
Member: Steven Rhodes
How It Works
A custom function is different from a model-defined function (see Chapter 11) in that a custom function is defined in the
storage model. This makes the custom function much more like a traditional stored procedure in a database. Just like a
DefiningQuery in the storage model defines a “virtual” table that doesn't really exist in the database, a custom function
in the storage model is like a “virtual” stored procedure. Some in the Entity Framework community refer to custom
functions as native functions . The Microsoft documentation uses the term “custom function,” so we'll go with that.
The code in Listing 10-13 defines our custom function. We put this in the storage model section of the .edmx
file by directly editing the file using the XML editor. Note that if you use the Update From Database Wizard to update
the model with new objects from your database, the wizard will overwrite this section. So be careful to save out any
changes that you've made to the storage model before you use the Update From Database Wizard.
Just like with the stored procedures in the previous recipes, we used the Function Import Wizard to map the
custom function to a CLR method. This defines the name of the CLR method and the expected return type. In our
case, the Custom Function returns a collection of instances of the Member entity.
In Listing 10-14, the code uses the MembersWithTheMostMessages() method to invoke the custom function. This
is the same pattern we used with stored procedures.
Custom functions can be helpful in the following scenarios:
You don't have permissions to create the stored procedures you need in the database.
You want to manage deployments of the code and the database separately. Using one or more
custom functions, you can deploy your code without deploying new stored procedures for the
database.
The existing stored procedures in the database have parameters that are incompatible with
your entities. Using custom functions, you can create an abstraction layer that drops, adds, or
changes types between the stored procedure parameters and the properties on your entity.
 
Search WWH ::




Custom Search