HOW TO:呼叫使用者定義函式 (Entity Framework)

Entity SQL 可讓您呼叫查詢中的使用者定義函式。 這些函式可以定義內嵌在查詢之中,或是做為概念模型的一部分。 如需詳細資訊,請參閱使用者定義函式 (Entity SQL)

本主題的範例根據 Adventure Works Sales Model。若要執行此主題中的程式碼,您必須已經將 Adventure Works Sales Model 加入到專案中,並設定您的專案使用 Entity Framework。如需詳細資訊,請參閱 HOW TO:使用實體資料模型精靈 (Entity Framework)HOW TO:手動設定 Entity Framework 專案HOW TO:手動設定 Entity Framework 專案

範例

下列範例定義 Entity SQL 查詢中名為 OrderTotal 的函式。 此函式藉由加入 SubTotalTaxAmtFreight 屬性的值,採用 SalesOrderHeader 物件並重新計算總金額。 然後呼叫查詢投影中的這個函式以傳回重新計算的 TotalDue 與從資料來源傳回的 TotalDue 值。 USING 運算子對指定傳遞給函式之 SalesOrderHeader 物件的命名空間而言是必要的。

' Query that calls the OrderTotal function to recalculate the order total. 
Dim queryString As String = "USING Microsoft.Samples.Entity;" & _
    " FUNCTION OrderTotal(o SalesOrderHeader) AS (o.SubTotal + o.TaxAmt + o.Freight)" & _
    " SELECT order.TotalDue AS currentTotal, OrderTotal(order) AS calculated" & _
    " FROM AdventureWorksEntities.SalesOrderHeaders AS order WHERE order.Contact.ContactID = @customer"

Dim customerId As Integer = 364


Using context As New AdventureWorksEntities()
    Dim query As New ObjectQuery(Of DbDataRecord)(queryString, context)
    query.Parameters.Add(New ObjectParameter("customer", customerId))

    For Each rec As DbDataRecord In query
        Console.WriteLine("Order Total: Current - {0}, Calculated - {1}.", rec(0), rec(1))
    Next
End Using
// Query that calls the OrderTotal function to recalculate the order total.
string queryString = @"USING Microsoft.Samples.Entity;
    FUNCTION OrderTotal(o SalesOrderHeader) AS
    (o.SubTotal + o.TaxAmt + o.Freight)

    SELECT [order].TotalDue AS currentTotal, OrderTotal([order]) AS calculated
    FROM AdventureWorksEntities.SalesOrderHeaders AS [order]
    WHERE [order].Contact.ContactID = @customer";

int customerId = 364;


using (AdventureWorksEntities context =
    new AdventureWorksEntities())
{
    ObjectQuery<DbDataRecord> query = new ObjectQuery<DbDataRecord>(queryString, context);
    query.Parameters.Add(new ObjectParameter("customer",customerId));

    foreach (DbDataRecord rec in query)
    {
        Console.WriteLine("Order Total: Current - {0}, Calculated - {1}.", 
            rec[0], rec[1]);
    }
}

另請參閱

工作

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

概念

使用者定義函式 (Entity SQL)

其他資源

How to: Define Custom Functions in the Conceptual Model
How to: Define Custom Functions in the Conceptual Model