8.12. Model-Defined Functions

Model-defined functions allow you to define reusable functions at a model level. To create them at present, you must modify the .edmx file directly, although this will probably change in future versions of EF. In our convoluted example, we will create a new property for our Film entity that will return the Film title and description separated by a space.

  1. Right-click the Chapter8Model.edmx file and select Open With.

  2. Select XML Editor.

  3. Find the following section:

    <edmx:ConceptualModels>
          <Schema Namespace="BookModel" Alias="Self"
    xmlns:annotation="http://schemas.microsoft.com/ado/2009/02/edm/annotation"
    xmlns="http://schemas.microsoft.com/ado/2008/09/edm">

  4. Add the following inside the previous section:

    <Function Name="LongFilmDescription" ReturnType="Edm.String">
        <Parameter Name="Film" Type="BookModel.Film">
        </Parameter>
        <DefiningExpression>
          Trim(Film.Title) + " " + Film.Description
        </DefiningExpression>
    </Function>

  5. Open Program.cs and add the following using directive:

    using System.Data.Objects.DataClasses;

  6. Unfortunately, L2E doesn't yet know about the LongFilmDescription function, so we have to tell it by creating a static class decorated with the [EdmFunction] attribute to allow us to access it. Add the following code in Program.cs:

    public static class MDF
    {
        [EdmFunction("BookModel", "LongFilmDescription")]
        public static string LongFilmDescription(Film f)
        {
            throw new NotSupportedException("This function can only be used in a query");
        }
    }

  7. Once this is done, you can now utilize your function in L2E queries as follows:

    var query = from f in ctx.Films
    select new { FullName = MDF.LongFilmDescription(f) };

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.83.96