Export (0) Print
Expand All

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.

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.
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 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)
    };
}


Show:
© 2014 Microsoft