title: Entity Framework - Stop Lazy Loading Related Entities On Demand?
body: <p>I have Entity Framework set up and it works fine most of the time I need it. I have a structure like so</p>
  
  <pre><code>public partial class Topic : Entity
  {
      public Guid Id { get; set; }
      public string Name { get; set; }
      public DateTime CreateDate { get; set; }
      public virtual Post LastPost { get; set; }
      public virtual Category Category { get; set; }
      public virtual IList&lt;Post&gt; Posts { get; set; }
      public virtual IList&lt;TopicTag&gt; Tags { get; set; }
      public virtual MembershipUser User { get; set; }
      public virtual IList&lt;TopicNotification&gt; TopicNotifications { get; set; }
      public virtual IList&lt;Favourite&gt; Favourites { get; set; }
      public virtual Poll Poll { get; set; }
  }
  </code></pre>
  
  <p>As you can see I have a number of related entities which are lists. These are mapped as standard and are lazy loaded so I can call Topic.Posts or Topic.TopicNotifications etc... (Mappings below)</p>
  
  <pre><code>HasOptional(t =&gt; t.LastPost).WithOptionalDependent().Map(m =&gt; m.MapKey("Post_Id"));
  HasOptional(t =&gt; t.Poll).WithOptionalDependent().Map(m =&gt; m.MapKey("Poll_Id"));            
  HasRequired(t =&gt; t.Category).WithMany(t =&gt; t.Topics).Map(m =&gt; m.MapKey("Category_Id"));
  HasRequired(t =&gt; t.User).WithMany(t =&gt; t.Topics).Map(m =&gt; m.MapKey("MembershipUser_Id"));
  HasMany(x =&gt; x.Posts).WithRequired(x =&gt; x.Topic).Map(x =&gt; x.MapKey("Topic_Id")).WillCascadeOnDelete();
  HasMany(x =&gt; x.TopicNotifications).WithRequired(x =&gt; x.Topic).Map(x =&gt; x.MapKey("Topic_Id")).WillCascadeOnDelete();
  HasMany(t =&gt; t.Tags)
      .WithMany(t =&gt; t.Topics)
      .Map(m =&gt;
                  {
                      m.ToTable("Topic_Tag");
                      m.MapLeftKey("TopicTag_Id");
                      m.MapRightKey("Topic_Id");
                  });
  </code></pre>
  
  <p>This is all an well. But on a couple of occasions I have the need to manually populate Topic.Posts and Topic.Favorites.</p>
  
  <p>But if I try and set <code>Topic.Posts = SomeCollection</code> it triggers the lazy load and loads all the posts first, and then lets me set my collection so I get two sets of sql executed (The first I don't want)</p>
  
  <p>Is there anyway, to switch off the lazy loading manually on demand for just when I want to set the collection manually?</p>
  
  <p>Hope that makes sense... :/</p>