title: Conditionally Include() in Entity Framework
body: <p>I'm using EF4.3 with DbContext.</p>
  
  <p>I have an entity that I store in cache, so I need to eager load the necessary data before converting to a list and popping it in cache.</p>
  
  <p>My database is normalised so data is spread over several tables. The base entity is "User", a User may or may not be a "Subscriber" and a Subscriber can be one of 3 types "Contributor", "Member" or "Administrator"</p>
  
  <p>At present the whole fetch is not very elegant due to my lack of knowledge in EF, Linq et al.</p>
  
  <pre><code>    public static User Get(Guid userId)
      {
          Guard.ThrowIfDefault(userId, "userId");
  
          var r = new CrudRepo&lt;User&gt;(Local.Items.Uow.Context);
  
          var u = r.FindBy(x =&gt; x.UserId == userId)
              .Include("BookmarkedDeals")
              .Include("BookmarkedStores")
              .SingleOrDefault();
  
          if (u.IsNotNull() &amp;&amp; u.IsActive)
          {
              if (u.IsAdmin)
              {
                  u.GetAdministrator();
              }
              else if (u.IsContributor)
              {
                  u.GetContributor();
              }
              else if (u.IsMember)
              {
                  u.GetMember();
              }
              else
              {
                  string.Format("Case {0} not implemented", u.UserRoleId)
                      .Throw&lt;NotImplementedException&gt;();
              }
          }
  
          return u;
      }
  </code></pre>
  
  <p>Each of the 'Get' methods gets a Subscriber entity plus the relevant Include() entities for the role type.</p>
  
  <p>I'm pretty sure it can be done a whole lot more elegently than this but struggling with the initial thought process.</p>
  
  <p>Anyone help? </p>
  
  <p>UPDATED with example of one of the Get methods</p>
  
  <pre><code>    public static void GetMember(this User user)
      {
          Guard.ThrowIfNull(user, "user");
  
          var r = new ReadRepo&lt;Subscriber&gt;(Local.Items.Uow.Context);
  
          user.Subscriber = r.FindBy(x =&gt; x.UserId == user.UserId)
              .Include("Kudos")
              .Include("Member.DrawEntries")
              .Include("Member.FavouriteCategories")
              .Include("Member.FavouriteStores")
              .Single();
      }
  </code></pre>