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.