Up LINQ query examples

Closures

Last modified on August 15, 2012 17:21

Examples of using closures with a LINQ query are shown below.  In the examples below _em1 is an EntityManager.

C#
class MyClass {
 public static decimal Val = 50;

 public decimal GetVal() {
   return MyClass.Val;
  }
}

[Description("Uses a local variable as a query parameter.")]
public void LinqToEntities91() {
  MyClass c = new MyClass();

  var query = _em1.Orders
      .Where(o => o.Freight > MyClass.Val).Select(o => o);
  Assert.IsTrue(query.Count() == 360);
}

[Description("Uses a the value of the local variable at query execution time.")]
public void LinqToEntities92() {
 decimal x = 50;
  var query = _em1.Orders.Where(o => o.Freight > x).Select(o => new { o.Freight, o });
  Assert.IsTrue(query.Count() == 360);
  x = 100;
  Assert.IsTrue(query.Count() == 187);
}
VB
Friend Class MyClass
 Public Shared Val As Decimal = 50

 Public Function GetVal() As Decimal
Return MyClass.Val
 End Function
End Class

<Description("Uses a local variable as a query parameter.")>
Public Sub LinqToEntities91()
 Dim c As New MyClass()

 Dim query = _em1.Orders.Where(Function(o) o.Freight > MyClass.Val).Select(Function(o) o)
  Assert.IsTrue(query.Count() = 360)
End Sub

<Description("Uses a the value of the local variable at query execution time.")>
Public Sub LinqToEntities92()
 Dim x As Decimal = 50
 Dim query = _em1.Orders.Where(Function(o) o.Freight > x).Select(Function(o) New With {Key o.Freight, Key o})
  Assert.IsTrue(query.Count() = 360)
  x = 100
  Assert.IsTrue(query.Count() = 187)
End Sub
Tags: Query
Created by DevForce on February 18, 2011 08:27

This wiki is licensed under a Creative Commons 2.0 license. XWiki Enterprise 3.2 - Documentation. Copyright © 2020 IdeaBlade