Share via


Local Method Calls (LINQ to SQL)

A local method call is one that is executed within the object model. A remote method call is one that LINQ to SQL translates to SQL and transmits to the database engine for execution. Local method calls are needed when LINQ to SQL cannot translate the call into SQL. Otherwise, an InvalidOperationException is thrown.

Example 1

In the following example, an Order class is mapped to the Orders table in the Northwind sample database. A local instance method has been added to the class.

In Query 1, the constructor for the Order class is executed locally. In Query 2, if LINQ to SQL tried to translate LocalInstanceMethod()into SQL, the attempt would fail and an InvalidOperationException exception would be thrown. But because LINQ to SQL provides support for local method calls, Query2 will not throw an exception.

' Query 1. 
Dim q0 = _
    From ord In db.Orders _
    Where ord.EmployeeID = 9 _
    Select ord

For Each ordObj In q0
    Console.WriteLine("{0}, {1}", ordObj.OrderID, _
        ordObj.ShipVia.Value)
Next
// Query 1. 
var q1 =
    from ord in db.Orders
    where ord.EmployeeID == 9
    select ord;

foreach (var ordObj in q1)
{
    Console.WriteLine("{0}, {1}", ordObj.OrderID,
        ordObj.ShipVia.Value);
}
' Query 2. 
Public Function LocalInstanceMethod(ByVal x As Integer) As Integer 
    Return x + 1
End Function 

Sub q2()
    Dim db As New Northwnd("")
    Dim q2 = _
    From ord In db.Orders _
    Where ord.EmployeeID = 9 _
    Select member0 = ord.OrderID, member1 = ord.LocalInstanceMethod(ord.ShipVia.Value)
End Sub
// Query 2. 
public int LocalInstanceMethod(int x)
{
    return x + 1;
}

void q2()
{
    var q2 =
    from ord in db.Orders
    where ord.EmployeeID == 9
    select new
    {
        member0 = ord.OrderID,
        member1 = ord.LocalInstanceMethod(ord.ShipVia.Value)
    };
}

See Also

Other Resources

Background Information (LINQ to SQL)