HOW TO:在查詢中呼叫模型定義函式 (LINQ to Entities)

本主題描述如何從 LINQ to Entities 查詢內呼叫概念模型中所定義的函式。

以下程序提供從 LINQ to Entities 查詢內呼叫模型定義函式的高階概述。 程序後的範例提供程序中之步驟相關詳細資訊。 程序假設您已在概念模型中定義函式。 如需詳細資訊,請參閱 How to: Define Custom Functions in the Conceptual Model

呼叫概念模型中定義的函式

  1. 將 Common Language Runtime (CLR) 方法加入至您的應用程式,該方法會對應至概念模型中所定義之函式。 若要對應方法,您必須將 EdmFunctionAttribute 套用至方法。 請注意,屬性的 NamespaceNameFunctionName 參數分別是概念模型的命名空間名稱和概念模型中的函式名稱。 LINQ 的函式名稱解析是區分大小寫的。

  2. 在 LINQ to Entities 查詢中呼叫函式。

範例

下列範例示範如何從 LINQ to Entities 查詢內呼叫概念模型中所定義的函式。 範例使用 School 模型。 如需關於 School 模型的詳細資訊,請參閱建立 School 範例資料庫 (Entity Framework 快速入門)產生 School .edmx 檔案 (Entity Framework 快速入門)

下列概念模型函式會傳回講師受雇之後經過的年份。 如需將函式加入至概念模型的詳細資訊,請參閱 How to: Define Custom Functions in the Conceptual Model

<Function Name="YearsSince" ReturnType="Edm.Int32">
  <Parameter Name="date" Type="Edm.DateTime" />
  <DefiningExpression>
    Year(CurrentDateTime()) - Year(date)
  </DefiningExpression>
</Function>

接下來,將下列方法加入至您的應用程式並使用 EdmFunctionAttribute 將它對應至概念模型函式:

<EdmFunction("SchoolModel", "YearsSince")>
Public Function YearsSince(ByVal date1 As DateTime) _
    As Integer
    Throw New NotSupportedException("Direct calls are not supported.")
End Function
[EdmFunction("SchoolModel", "YearsSince")]
public static int YearsSince(DateTime date)
{
    throw new NotSupportedException("Direct calls are not supported.");
}

現在,您可以從 LINQ to Entities 查詢內呼叫概念模型函式。 下列程式碼會呼叫該方法,顯示受雇超過十年的所有講師:

Using context As New SchoolEntities()
    ' Retrieve instructors hired more than 10 years ago.
    Dim instructors = From p In context.People _
        Where YearsSince(CType(p.HireDate, DateTime?)) > 10 _
        Select p

    For Each instructor In instructors
        Console.WriteLine(instructor.LastName)
    Next
End Using
using (SchoolEntities context = new SchoolEntities())
{
    // Retrieve instructors hired more than 10 years ago.
    var instructors = from p in context.People
                      where YearsSince((DateTime)p.HireDate) > 10
                      select p;

    foreach (var instructor in instructors)
    {
        Console.WriteLine(instructor.LastName);
    }
}

另請參閱

工作

HOW TO:呼叫模型定義函式做為物件方法 (LINQ to Entities)

概念

LINQ to Entities 中的查詢
呼叫 LINQ to Entities 查詢中的函式

其他資源

.edmx File Overview