다음을 통해 공유


방법: 데이터베이스 함수 호출

SqlFunctions 클래스에는 LINQ to Entities 쿼리에 사용할 SQL Server 함수를 노출하는 메서드가 포함되어 있습니다. LINQ to Entities 쿼리에서 SqlFunctions 메서드를 사용할 때 해당되는 데이터베이스 함수가 데이터베이스에서 실행됩니다.

참고 항목

값 집합에 대한 계산을 수행하고 집계 데이터베이스 함수라고도 하는 단일 값을 반환하는 데이터베이스 함수를 직접 호출할 수 있습니다. 기타 정식 함수는 LINQ to Entities 쿼리의 일부로만 호출할 수 있습니다. 집계 함수를 직접 호출하려면 ObjectQuery<T>를 함수로 전달해야 합니다. 자세한 내용은 아래 두 번째 예제를 참조하세요.

참고 항목

SqlFunctions 클래스의 메서드는 SQL Server 함수와 관련되어 있습니다. 데이터베이스 함수를 노출하는 유사한 클래스가 다른 공급자를 통해 제공될 수 있습니다.

예 1

다음 예에서는 AdventureWorks 판매 모델을 사용합니다. 이 예제에서는 CharIndex 메서드를 사용하여 성이 "Si"로 시작하는 모든 담당자를 반환하는 LINQ to Entities 쿼리를 실행합니다.

using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    // SqlFunctions.CharIndex is executed in the database.
    var contacts = from c in AWEntities.Contacts
                   where SqlFunctions.CharIndex("Si", c.LastName) == 1
                   select c;

    foreach (var contact in contacts)
    {
        Console.WriteLine(contact.LastName);
    }
}
Using AWEntities As New AdventureWorksEntities()

    ' SqlFunctions.CharIndex is executed in the database.
    Dim contacts = From c In AWEntities.Contacts _
                   Where SqlFunctions.CharIndex("Si", c.LastName) = 1 _
                   Select c

    For Each contact In contacts
        Console.WriteLine(contact.LastName)
    Next
End Using

예제 2

다음 예에서는 AdventureWorks 판매 모델을 사용합니다. 이 예제에서는 집계 ChecksumAggregate 메서드를 직접 호출합니다. ObjectQuery<T>는 LINQ to Entities 쿼리에 포함되지 않고 호출되도록 지정하는 함수로 전달됩니다.

using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
    // SqlFunctions.ChecksumAggregate is executed in the database.
    decimal? checkSum = SqlFunctions.ChecksumAggregate(
        from o in AWEntities.SalesOrderHeaders
        select o.SalesOrderID);

    Console.WriteLine(checkSum);
}
Using AWEntities As New AdventureWorksEntities()

    ' SqlFunctions.ChecksumAggregate is executed in the database.
    Dim checkSum As Integer = SqlFunctions.ChecksumAggregate( _
        From o In AWEntities.SalesOrderHeaders _
        Select o.SalesOrderID)

    Console.WriteLine(checkSum)
End Using

참고 항목