title: Using varying values in expressions in Entity Framework
body: <p>This question was a inspired by the question: "<a href="https://stackoverflow.com/questions/18238415/including-a-method-class-inside-an-expression">Including a Method class inside an Expression</a>". This question is not just "how can I find a solution to this" as that question already has that answer. My question is "<strong>How do I write a <code>Expression</code> that uses a captured variable more than once but does not repeatedly query the variable within a single evaluation</strong>".</p>
  
  <p>Lets say I have a property value that can vary over time or is very expensive to pull, what would be the correct way to use it multiple times in a Expression query. </p>
  
  <p>Let me show by example</p>
  
  <pre><code>namespace Sandbox_Console
  {    
      public class Program
      {
          static void Main(string[] args)
          {
              using (var ctx = new Context())
              {
                  var selectExpression = GetSelect();
  
                  var query = ctx.Sources.Select(selectExpression);
                  var queryText = query.ToString();
                  var result1 = query.First();
                  var result2 = query.First();
  
                  var goodResult = (result1.Id != result2.Id &amp;&amp; result1.Id == (result1.Prop - 1));
  
                  if(!goodResult)
                      throw new InvalidDataException();
              }
          }
  
          static public Expression&lt;Func&lt;Source, Result&gt;&gt; GetSelect()
          {
              var foo = new Foo();
  
              return source =&gt; new Result {Id = source.Id + foo.PropertyThatVaries, Prop = foo.PropertyThatVaries};
          }
      }
  
     //...
  }
  </code></pre>
  
  <p>In the above code the entity framework source is queried twice by the same query, but it should have two different values for some of the passed in parameters. Here is the sql that is generated from the query</p>
  
  <pre><code>SELECT 
  [Extent1].[Id] AS [Id], 
  [Extent1].[Id] + @p__linq__0 AS [C1], 
  @p__linq__1 AS [C2]
  FROM [dbo].[Sources] AS [Extent1]
  </code></pre>
  
  <p>The problem is <code>@p__linq__0</code> and <code>@p__linq__1</code> are two different values from two subsequent calls to the <code>PropertyThatVaries</code> property.</p>
  
  <p>I can get a similar result by not directly putting in the varying property to the query, but if I do that I don't get different values on subsequent queries.</p>
  
  <pre><code>static public Expression&lt;Func&lt;Source, Result&gt;&gt; GetSelect()
  {
      var foo = new Foo();
      var tmp = foo.PropertyThatVaries;
  
      return source =&gt; new Result { Id = source.Id + tmp, Prop = tmp };
      //Now fails the "result1.Id != result2.Id" test.
  }
  </code></pre>
  
  <p>How would you go about getting a linq statement that looked like this in sql:</p>
  
  <pre><code>SELECT 
  [Extent1].[Id] AS [Id], 
  [Extent1].[Id] + @p__linq__0 AS [C1], 
  @p__linq__0 AS [C2]
  FROM [dbo].[Sources] AS [Extent1]
  </code></pre>
  
  <p>But still got the current value from <code>foo.PropertyThatVaries</code>?</p>
  
  <hr>
  
  <p>Here is a full complileable version of the test program, it was made in .NET 4.5</p>
  
  <pre><code>using System;
  using System.Data.Entity;
  using System.IO;
  using System.Linq;
  using System.Linq.Expressions;
  
  namespace Sandbox_Console
  {    
      public class Program
      {
          static void Main(string[] args)
          {
              using (var ctx = new Context())
              {
                  var selectExpression = GetSelect();
  
                  var query = ctx.Sources.Select(selectExpression);
                  var queryText = query.ToString();
                  var result1 = query.First();
                  var result2 = query.First();
  
                  var goodResult = (result1.Id != result2.Id &amp;&amp; result1.Id == (result1.Prop + 1));
  
                  if(!goodResult)
                      throw new InvalidDataException();
              }
          }
  
          static public Expression&lt;Func&lt;Source, Result&gt;&gt; GetSelect()
          {
              var foo = new Foo();
              var tmp = foo.PropertyThatVaries;
  
              return source =&gt; new Result { Id = source.Id + tmp, Prop = tmp };
              //return source =&gt; new Result {Id = source.Id + foo.PropertyThatVaries, Prop = foo.PropertyThatVaries};
          }
      }
  
      public class Context : DbContext
      {
          public Context()
          {
              Database.SetInitializer&lt;Context&gt;(new Init());
          }
  
          public DbSet&lt;Source&gt; Sources { get; set; }
      }
  
      public class Init : DropCreateDatabaseAlways&lt;Context&gt;
      {
          protected override void Seed(Context context)
          {
              base.Seed(context);
              context.Sources.Add(new Source() { Id = 1 });
          }
      }
  
      public class Source
      {
          public int Id { get; set; }
      }
  
      public class Result
      {
          public int Id { get; set; }
          public int Prop { get; set; }
      }
  
      public class Foo
      {
          public Foo()
          {
              rnd = new Random();
          }
  
          public int PropertyThatVaries
          {
              get
              {
                  //This could also be a "Expensive" get. Un-comment the next line to simulate.
                  //Thread.Sleep(1000);
  
                  return rnd.Next(1, 100000);
              }
          }
  
          private Random rnd;
      }
  }
  </code></pre>