Loading strategy for specifying how to load data, for example eager loading and define queries etc.
Here is a simple generic Repository (I left out some other methods, they aren't important in this current context) using Entity Framework 4.0, where a Loading strategy is added:
public class Repository<TEntity> where TEntity : class
{
readonly ObjectContext _objectContext;
readonly ObjectSet<TEntity> _objectSet;
public Repository(ObjectContext objectContext)
{
Contract.Requires(objectContext != null);
_objectContext = objectContext;
_objectSet = _objectContext.CreateObjectSet<TEntity>();
}
public IEnumerable<TEntity> Find(ILoadingStrategy<TEntity> loadingStrategy)
{
var query = loadingStrategy.CreateStrategy(_objectSet);
return query.ToList();
}
...
}
Here is the ILoadingStrategy interface (I know it's a leaky abstraction but in this case if we decide to use Entity Framework and the likeliness of changing to another O/R-mapper is very minimal.
public interface ILoadingStrategy<TEntity> where TEntity : class
{
IQueryable<TEntity> CreateStrategy(ObjectSet<TEntity> objectSet);
}
Here is an example of a Loading strategy, it will make sure it will include some tables and also perform a search:
public class SharedCodeSearchOnTitle : ILoadingStrategy<SharedCode>
{
private readonly string _search;
public SharedCodeSearchOnTitle (string search = null)
{
_search = search;
}
public IQueryable<SharedCode> CreateStrategy(ObjectSet<SharedCode> objectSet)
{
var query = objectSet.Include("Tags")
.Where(sharedCode => sharedCode.Approved);
if (!string.IsNullOrWhiteSpace(_search))
query = query.Where(c => c.Title.Contains(_search));
return query;
}
In code it can be used:
var sharedCodes = new Repository<SharedCode>(...);
var result = sharedCodes.Find(new SharedCodeSearchOnTitle(search));
What's the idea of the code?
The idea is to avoid having queries floating around in different places and also to reuse the generic Repository instead of adding query methods to different Repositories implementations.
Fork
0 Feedback
You must log in before you can give any feedback
You must log in before you can post a comment


694
1




Mark 'c#' tag as 'like'
Mark 'c#' tag as 'ignore'