0

I am trying to figure out how to use the new EF Code First stuff and I am having trouble figuring out how to adapt the Include functionality into a semi-generic Repository class. (I say semi-generic, because the class is not generic, just the methods. So I have one repository that wraps an aggregate, essentially, and you can interact with all Entities that are part of that aggregate, not just a single Entity.)

My situation is I have an Entity that has one child that always needs to be loaded, and then other children that are only optionally loaded, I want to include a simple bool parameter on my repository method. Like so:

public S GetByID<S>(int entityID, bool loadChildren = false) where S : class
{
  DbSet<S> set = _context.Set<S>();

  if (loadChildren)
    set = FullInclude<S>(set);
  else
    set = DefaultInclude<S>(set);

  return set.Find(entityID);
}

protected virtual DbSet<S> DefaultInclude<S>(DbSet<S> set) where S : class
{
  // base implementation just returns the set
  // derived versions would attach Includes to the set before returning it
  return set;
}

protected virtual DbSet<S> FullInclude<S>(DbSet<S> set) where S : class
{
  // base implementation just returns the set
  // derived versions would attach Includes to the set before returning it
  return set;
}

That is my base Repository, and I'd like to be able to override those XyzInclude methods in a derived class. But I need to override them with a non-generic implementation, and this obviously doesn't work at a language level.

This was really easy with Linq2Sql in that I'd just configure a DataLoadOptions object and attach it to the context. With the Include API off of DbSet I'm stumped on how best to do this. I'm looking for recommendations on a simple implementation of a Strategy pattern or similar.

EDIT: I guess the essence of my question is really about overriding a generic method with a non-generic derived version. I'm looking for a pattern or technique that allows me to do that. Extension methods are one thing I'm looking at, but would prefer a more "pure" solution if anyone has one.

sliderhouserules
  • 3,415
  • 24
  • 32

2 Answers2

0

Not possible unless you make the class fully generic,:

public class BaseRepo<S>
{
    protected virtual DbSet<S> DefaultInclude(DbSet<S> set) {return set;}
} 

public class ProductRepo : BaseRepo<Product>
{
    protected override DbSet<Product> DefaultInclude(DbSet<Product> set)
    {
       return set.Include("...");
    }
}
jeroenh
  • 26,362
  • 10
  • 73
  • 104
  • I'm more looking for a different solution than the above. I can't make the Repository fully generic. I had the fully generic Repository in a previous incarnation and had to go the non-generic direction for various reasons. Plus, I need the ability to set Includes for any Entity. My Repository design isn't the semi-typical single-repository-per-entity that lots of people go with. Thanks for the answer though. I appreciate it. – sliderhouserules Apr 27 '11 at 15:56
  • I can only say what you're asking is simply not possible in your current design. You may want to rethink the whole concept. – jeroenh Apr 27 '11 at 18:26
0

Just thought I'd revisit this with the solution I ended up with. My repositories aren't fully generic, but all the methods are, so I needed a way to store includes for any entity type and be able to pull them out when the methods were called for that type.

I borrowed from Ladislav's answer here, and I may revisit this design to just have each individual method defined on the derived repositories define their own includes as there are enough different combinations of what to include and what not to include that repeating the little bit of code defining the same include in a few places is probably worth it. But anyway, this is the current design and it works...

Base repository:

public abstract class Repository : IQueryableRepository, IWritableRepository
{
  private readonly DbContext _context;
  private readonly Dictionary<Type, LambdaExpression[]> _includes = new Dictionary<Type, LambdaExpression[]>();

  protected Repository(DbContextBase context)
  {
    _context = context;
    RegisterIncludes(_includes);
  }

  protected abstract void RegisterIncludes(Dictionary<Type, LambdaExpression[]> includes);

  protected S GetSingle<S>(Expression<Func<S, bool>> query, bool getChildren = false) where S : class
  {
    IQueryable<S> entities = _context.Set<S>().AsNoTracking();

    if (query != null)
      entities = entities.Where(query);

    entities = ApplyIncludesToQuery<S>(entities, getChildren);

    return entities.FirstOrDefault();
  }

  private IQueryable<S> ApplyIncludesToQuery<S>(IQueryable<S> entities, bool getChildren) where S : class
  {
    Expression<Func<S, object>>[] includes = null;

    if (getChildren && _includes.ContainsKey(typeof(S)))
      includes = (Expression<Func<S, object>>[])_includes[typeof(S)];

    if (includes != null)
      entities = includes.Aggregate(entities, (current, include) => current.Include(include));

    return entities;
  }
}

Derived repositories only need to define their includes in the one place, and then when you call the query method you just specify if you want children included or not (see getChildren above).

public class DerivedRepository : Repository
{
  public DerivedRepository(DbContext context)
    : base(context) { }

  protected override void RegisterIncludes(Dictionary<Type, LambdaExpression[]> includes)
  {
    includes.Add(typeof(ParentType), new Expression<Func<ParentType, object>>[] { 
      p => p.SomeChildReference.SomeGrandchild,
      p => p.SomeOtherChildReference
    });
  }
}
Community
  • 1
  • 1
sliderhouserules
  • 3,415
  • 24
  • 32
  • This is an interesting approach, however the thing I'm not too keen on is that the includes are in one location. The problem I have with it is that depending on the circumstance you may want different includes e.g. while getting a list of paged customers you don't want the profile, post and invoice information... however for a user details page you do want all of the information – Paul Carroll Jul 05 '11 at 05:31
  • Yeah, that's the dilemma that I debated in my head for a bit trying to figure out the best way to do this. I went with the simplest option for now (defining them in a single place) but the evolved design would have each method define their own includes, and send it down to the base repository as a parameter, instead of it being a class-level variable. The answer from Ladislav that I linked to above covers the gist of that. – sliderhouserules Aug 23 '11 at 17:29