entity-framework/ef6/modeling/designer/advanced/tvfs.md
[!NOTE] EF5 Onwards Only - The features, APIs, etc. discussed in this page were introduced in Entity Framework 5. If you are using an earlier version, some or all of the information does not apply.
The video and step-by-step walkthrough shows how to map table-valued functions (TVFs) using the Entity Framework Designer. It also demonstrates how to call a TVF from a LINQ query.
TVFs are currently only supported in the Database First workflow.
TVF support was introduced in Entity Framework version 5. Note that to use the new features like table-valued functions, enums, and spatial types you must target .NET Framework 4.5. Visual Studio 2012 targets .NET 4.5 by default.
TVFs are very similar to stored procedures with one key difference: the result of a TVF is composable. That means the results from a TVF can be used in a LINQ query while the results of a stored procedure cannot.
Presented By: Julia Kornich
To complete this walkthrough, you need to:
Install the School database.
Have a recent version of Visual Studio
CREATE FUNCTION [dbo].[GetStudentGradesForCourse]
(@CourseID INT)
RETURNS TABLE
RETURN
SELECT [EnrollmentID],
[CourseID],
[StudentID],
[Grade]
FROM [dbo].[StudentGrade]
WHERE CourseID = @CourseID
Open the file where the Main method is defined. Add the following code into the Main function.
The following code demonstrates how to build a query that uses a Table-valued Function. The query projects the results into an anonymous type that contains the related Course title and related students with a grade greater or equal to 3.5.
using (var context = new SchoolEntities())
{
var CourseID = 4022;
var Grade = 3.5M;
// Return all the best students in the Microeconomics class.
var students = from s in context.GetStudentGradesForCourse(CourseID)
where s.Grade >= Grade
select new
{
s.Person,
s.Course.Title
};
foreach (var result in students)
{
Console.WriteLine(
"Couse: {0}, Student: {1} {2}",
result.Title,
result.Person.FirstName,
result.Person.LastName);
}
}
Compile and run the application. The program produces the following output:
Couse: Microeconomics, Student: Arturo Anand
Couse: Microeconomics, Student: Carson Bryant
In this walkthrough we looked at how to map Table-valued Functions (TVFs) using the Entity Framework Designer. It also demonstrated how to call a TVF from a LINQ query.