title: Why is my Entity Framework Code First proxy collection null and why can't I set it?
body: <p>I am using DBContext and have two classes whose properties are all virtual. I can see in the debugger that I am getting a proxy object when I query the context. However, a collection property is still null when I try to add to it. I thought that the proxy would ensure that collection is initialized.</p>
  
  <p>Because my Poco object can be used outside of its data context, I added a check for the collection being null in the constructor and create it if necessary: </p>
  
  <pre><code>public class DanceStyle
  {
      public DanceStyle()
      {
          if (DanceEvents == null)
          {
              DanceEvents = new Collection&lt;DanceEvent&gt;();
          }
      }
      ...
      public virtual ICollection&lt;DanceEvent&gt; DanceEvents { get; set; }
  }
  </code></pre>
  
  <p>That works outside the data context but if I retrieve an object using a query, although the test is true, when I try to set it, I get following exception: 'The property 'DanceEvents' on type 'DanceStyle_B6089AE40D178593955F1328A70EAA3D8F0F01DDE9F9FBD615F60A34F9178B94' cannot be set because the collection is already set to an EntityCollection.'</p>
  
  <p>I can see it is null and I cannot add to it, but neither can I set it to a collection because the proxy says it is already set. Therefore I cannot use it. I'm confused.</p>
  
  <p>Here is the DanceEvent class:</p>
  
  <pre><code>public class DanceEvent
  {
      public DanceEvent()
      {
          if (DanceStyles == null)
          {
              DanceStyles = new Collection&lt;DanceStyle&gt;();
          }
      }
      ...
      public virtual ICollection&lt;DanceStyle&gt; DanceStyles { get; set; }
  }
  </code></pre>
  
  <p>I have omitted the other value-type properties from the code above. I have no other mappings for those classes in the context class.</p>