EF 6 - Table-Valued Function

Table-Valued Function trong Entity Framework

Table-Valued Function (TVF) tương tự như stored procedure, ngoại trừ một điểm khác biệt chính: kết quả của table-valued function có thể được sử dụng trong truy vấn LINQ-to-Entity.

Sau đây là một table-valued function mẫu có tên GetCourseListByStudentID trong cơ sở dữ liệu SQL Server, sẽ trả về tất cả các khóa học của một sinh viên cụ thể.

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
)

Bây giờ, bạn hãy thêm table-valued function này vào EDM bằng cách nhấp chuột phải vào trình thiết kế -> chọn Update Model from the Database.. như hình bên dưới.

Entity Framework 5.0 Tutorial

Trong trình hướng dẫn cập nhật, mở rộng Stored Procedures and Functions -> Schema -> chọn GetCourseListByStudentID và nhấp vào Finish. Đừng quên đánh dấu vào hộp kiểm Import selected procedures and functions into the entity model.

Entity Framework 5.0 Tutorial

Điều này sẽ thêm table-valued function như một chức năng và tạo ra một kiểu dữ liệu phức tạp GetCourseListByStudentID_Result cho kết quả.

table-valued function GetCourseListByStudentID của chúng tôi trả về các cột từ bảng Course do đó chúng tôi có thể ánh xạ thực thể Course với kết quả thay vì sử dụng một kiểu dữ liệu phức tạp.

Để làm điều này bạn hãy mở trình duyệt mô hình -> Function Imports -> nhấp chuột phải vào 'GetCferenceListByStudentID' -> nhấp vào Edit:

Entity Framework 5.0 Tutorial

Bạn sẽ thấy rằng EDM đã tự động tạo ra kiểu dữ liệu phức tạp GetCourseListByStudentID_Result như một kiểu danh sách trả về.

Entity Framework 5.0 Tutorial

Thay đổi Returns a Collection Of thành Entities và chọn thực thể Course, như hình bên dưới

Entity Framework 5.0 Tutorial

Bây giờ, bạn có thể thực thi một table-valued function như là một phương thức của DBContext, như được trình bày bên dưới:

using (var ctx = new SchoolDBEntities())
{
    //Execute TVF and filter result
    var courses = ctx.GetCourseListByStudentID(1)
                     .ToList<Course>();
}