Entity Framework Tutorial Basics(34):Table-Valued Function

追憶似水流年發表於2016-07-07

Table-Valued Function in Entity Framework 5.0

Entity Framework 5.0 supports Table-valued functions of SQL Server.

Table-valued functions are similar to stored procedure with one key difference: the result of TVF is composable which means that it can be used in a LINQ query.

We have created a TVF GetCourseListByStudentID in the database that will return all the courses of a particular student. For example:

USE [SchoolDB]
    GO
    /****** Object:  UserDefinedFunction [dbo].[GetCourseListByStudentID]  */  
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE FUNCTION [dbo].[GetCourseListByStudentID]
    (    
        -- Add the parameters for the function here
        @studentID int
    )
    RETURNS TABLE 
    AS
    RETURN 
    (
        -- Add the SELECT statement with parameter references here
        select c.courseid, c.coursename,c.Location, c.TeacherId
    from student s left outer join studentcourse sc on sc.studentid = s.studentid left outer join course c on c.courseid = sc.courseid
    where s.studentid = @studentID
    )

 

Now, update your EDM and add this TVF into your EDM. Right click on the designer → select Update Model from the Database..

Entity Framework 5.0 Tutorial

Expand Stored Procedures and Functions node → expand schema node (dbo schema in our case) → select 'GetCourseListByStudentID' and click Finish. Make sure that the checkbox for 'Import selected procedures and functions into the entity model' is checked (this will import the function automatically).

Entity Framework 5.0 Tutorial

After you imported the function, you can verify it: Open Model Browser → expand Function Imports → right click on imported function 'GetCourseListByStudentID' → click Edit:

Entity Framework 5.0 Tutorial

You can see that EDM has automatically created the complex type GetCourseListByStudentID_Result as a return collection type.

Entity Framework 5.0 Tutorial

You can also select an existing entity as a return type if TVF returns the same columns as entity:

Entity Framework 5.0 Tutorial

Now, you can use TVF with DBContext. For example:

using (var ctx = new SchoolDBEntities())
{
    //Execute TVF and filter result
    var courseList = ctx.GetCourseListByStudentID(1).Where(c => c.Location.SpatialEquals(DbGeography.FromText("POINT(-122.360 47.656)"))))
                            .ToList<GetCourseListByStudentID_Result>();

               
     foreach (GetCourseListByStudentID_Result cs in courseList)
                Console.WriteLine("Course Name: {0}, Course Location: {1}", 
                            cs.CourseName, cs.Location);
}

 

相關文章