HOW TO:使用搭配 In 和 Out 參數的預存程序執行查詢 (Entity Framework)
本主題提供兩個範例,示範如何使用 Entity Framework 執行參數化預存程序。 第一個範例接受一個輸入參數,然後傳回實體物件的集合。 第二個範例接受一個輸入參數和一個輸出參數,並在輸出參數中傳回一個值。 本主題的範例是以 School Model 為依據。 若要遵循這些範例,請將 School 模型 加入至專案中,並將專案設定成使用 Entity Framework 。 如需詳細資訊,請參閱 HOW TO:使用實體資料模型精靈 (Entity Framework)。
範例
下列程式碼會執行 GetStudentGrades 預存程序,其中 StudentId 是必要參數。 若要執行此程式碼範例,請匯入 GetStudentGrades
預存程序,並將 CourseGrade
實體指定為傳回型別。 如需如何匯入預存程序的詳細資訊,請參閱 How to: Import Stored Procedures。
' Specify the Student ID.
Dim studentId As Integer = 2
Using context As New SchoolEntities()
For Each grade As StudentGrade In context.GetStudentGrades(studentId)
Console.WriteLine("StudentID: " & studentId)
Console.WriteLine("Student grade: " & grade.Grade)
Next
End Using
// Specify the Student ID.
int studentId = 2;
using (SchoolEntities context =
new SchoolEntities())
{
foreach (StudentGrade grade in
context.GetStudentGrades(studentId))
{
Console.WriteLine("StudentID: " + studentId);
Console.WriteLine("Student grade: " + grade.Grade);
}
}
下列程式碼會執行 GetDepartmentName
預存程序,此程序會傳回輸出參數中的部門名稱。 若要執行此程式碼範例:
將以下程序加入至 School 資料庫:
CREATE PROCEDURE [dbo].[GetDepartmentName] @ID int, @Name nvarchar(50) OUTPUT AS SELECT @Name = Name FROM Department WHERE DepartmentID = @ID
藉由加入
GetDepartmentName
預存程序,從資料庫更新 School 模型。 如需詳細資訊,請參閱 How to: Update an .edmx File when the Database Changes。匯入
GetDepartmentName
預存程序並將 [None] 指定為此預存程序的傳回型別。 如需詳細資訊,請參閱 How to: Import a Stored Procedure。
Using context As New SchoolEntities()
' name is an output parameter.
Dim name As New ObjectParameter("Name", GetType(String))
context.GetDepartmentName(1, name)
Console.WriteLine(name.Value)
End Using
using (SchoolEntities context =
new SchoolEntities())
{
// name is an output parameter.
ObjectParameter name = new ObjectParameter("Name", typeof(String));
context.GetDepartmentName(1, name);
Console.WriteLine(name.Value);
}