码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2016-07-07 12:43:23      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:

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..

技术分享

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).

技术分享

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

技术分享

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

技术分享

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

技术分享

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);
}

 

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

标签:

原文地址:http://www.cnblogs.com/purplefox2008/p/5649244.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!