title: Avoiding ObjectDisposedException with LINQ (LINQ2SQL)
body: <p>I am running into the "Lazy IO Problem" in Linq and I haven't found a solution that I'm happy with</p>
  
  <h2>Setting up the problem</h2>
  
  <p>Let say we have SQL tables that looks like</p>
  
  <pre><code>create table Person (
      id int primary key not null,
      name text not null,
  )
  
  create table Dog (
      name text primary key not null,
      ownerid text primary key not null references Person(name)
  )
  </code></pre>
  
  <p>And in C# we want to use LINQ and Entity Framework to deal with this. Entity Framework classes are defined as <code>partial</code> so we can extend them to add a <code>.Get(string)</code> method and this makes for very clean code. </p>
  
  <pre><code>public partial class Dog 
  {
      public static Dog Get(string dogname) 
      {
          using (var db = new MyDataContext())
          {
              // LINQ is lazy and doesn't load the referenced Person
              return db.Dogs.Single(d =&gt; d.name == dogname);
          }
      }
  }
  </code></pre>
  
  <h2>Where the problem happens</h2>
  
  <p>Now we attempt to use the <code>Dog</code> object for something</p>
  
  <pre><code>public string DogJson(string dogname) 
  {
      var dog = Dog.Get(dogname);
      return JsonConvert.SerializeObject(dog);
  }
  </code></pre>
  
  <p>Since our instance <code>dog</code> contains <code>dog.Owner</code> because of the foreign key, <code>JsonConvert</code> will of course attempt to include it in the json string. But since the DataContext is disposed and LINQ is lazy, an <code>ObjectDisposedException</code> is of course raised because <code>dog.Person</code> had not been evaluated when we disposed the DataContext. </p>
  
  <p>In this case, we don't care about the <code>Owner</code> object at all, we just want to serialize the <code>Dog</code> to json. What is the best way to do that without?</p>
  
  <h2>My solution</h2>
  
  <p>I have a solution, but I don't particularly like it. Using projection into an anonamous object and casting back to <code>Dog</code>, because we are not allowed to explicitly construct a <code>Dog</code> in the query. </p>
  
  <pre><code>public static Dog Get(string dogname)
  {
      using (var db = new MyDataContext())
      {
          var tmpdog = db.Dogs.Where(d =&gt; d.name == dogname)
              .Select(d =&gt; new { name = d.name, ownerid = d.ownerid}).Single();
          return new Dog() { name = tmpdog.name, ownerid = tmpdog.ownerid};
      }
  }
  </code></pre>
  
  <p>I don't like this solution because it doesn't scale well. This example only has two properties and this gets quickly out of hand. LINQ usually makes for very elegant code and this is not elegant at all. It's also prone to programmer </p>
  
  <p>It sort of feels like I am taking the wrong approach here. </p>