방법: 사용자 정의 함수 호출(Entity Framework)

Entity SQL을 사용하면 쿼리에서 사용자 정의 함수를 호출할 수 있습니다. 이러한 함수를 쿼리에서 인라인으로 정의하거나 개념적 모델의 일부로 정의할 수 있습니다. 자세한 내용은 사용자 정의 함수(Entity SQL)를 참조하십시오.

이 항목의 예제는 Adventure Works Sales 모델을 기반으로 합니다. 이 항목의 코드를 실행하려면 프로젝트에 Adventure Works Sales 모델을 추가하고 프로젝트에서 Entity Framework를 사용하도록 구성해야 합니다. 자세한 내용은 방법: 엔터티 데이터 모델 마법사 사용(Entity Framework) 또는 방법: Entity Framework 프로젝트 수동 구성방법: 엔터티 데이터 모델 수동 정의(Entity Framework)를 참조하십시오.

예제

다음 예제에서는 Entity SQL 쿼리에서 OrderTotal이라는 함수를 정의합니다. 이 함수는 SalesOrderHeader 개체를 사용하며, SubTotal, TaxAmtFreight 속성의 값을 더해 합계 금액을 다시 계산합니다. 그런 다음 쿼리 프로젝션에서 이 함수를 호출하면 데이터 소스에서 반환된 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]);
    }
}

참고 항목

작업

방법: 쿼리에서 모델 정의 함수 호출(LINQ to Entities)

개념

사용자 정의 함수(Entity SQL)

기타 리소스

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