Includes in a (semi) generic Repository
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.
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("...");
}
}
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
});
}
}
精彩评论