嗯.. 根据我使用的 ORM 的类型,我以多种方式解决了这个问题。
主要思想是拥有一个存储库基类和一个查询方法,该方法采用许多参数来指示所有可能的 where/orderby/expand|include/paging/etc 选项。
这是一个使用 LINQ to NHibernate 的快速而肮脏的示例(当然整个存储库应该是实现细节):
public class RepositoryBase
{
private ISession Session;
public RepositoryBase()
{
Session = SessionPlaceHolder.Session;
}
public TEntity[] GetPaged<TEntity>(IEnumerable<Expression<Func<TEntity, bool>>> filters,
IEnumerable<Expression<Func<TEntity, object>>> relatedObjects,
IEnumerable<Expression<Func<TEntity, object>>> orderCriterias,
IEnumerable<Expression<Func<TEntity, object>>> descOrderCriterias,
int pageNumber, int pageSize, out int totalPages)
{
INHibernateQueryable<TEntity> nhQuery = Session.Linq<TEntity>();
if (relatedObjects != null)
foreach (var relatedObject in relatedObjects)
{
if (relatedObject == null) continue;
nhQuery = nhQuery.Expand(relatedObject);
}
IQueryable<TEntity> query = nhQuery;
if (filters != null)
foreach (var filter in filters)
{
if (filter == null) continue;
query = query.Where(filter);
}
bool pagingEnabled = pageSize > 0;
if (pagingEnabled)
totalPages = (int) Math.Ceiling((decimal) query.Count()/(decimal) pageSize);
else
totalPages = 1;
if (orderCriterias != null)
foreach (var orderCriteria in orderCriterias)
{
if (orderCriteria == null) continue;
query = query.OrderBy(orderCriteria);
}
if (descOrderCriterias != null)
foreach (var descOrderCriteria in descOrderCriterias)
{
if (descOrderCriteria == null) continue;
query = query.OrderByDescending(descOrderCriteria);
}
if (pagingEnabled)
query = query.Skip(pageSize*(pageNumber - 1)).Take(pageSize);
return query.ToArray();
}
}
通常,当您不需要分页等时,您需要添加许多链接重载作为快捷方式。
这是另一个肮脏的。抱歉,我不确定我是否可以公开最后的内容。这些是草稿,可以显示:
using Context = Project.Services.Repositories.EntityFrameworkContext;
using EntitiesContext = Project.Domain.DomainSpecificEntitiesContext;
namespace Project.Services.Repositories
{
public class EntityFrameworkRepository : IRepository
{
#region IRepository Members
public bool TryFindOne<T>(Expression<Func<T, bool>> filter, out T result)
{
result = Find(filter, null).FirstOrDefault();
return !Equals(result, default(T));
}
public T FindOne<T>(Expression<Func<T, bool>> filter)
{
T result;
if (TryFindOne(filter, out result))
return result;
return default(T);
}
public IList<T> Find<T>() where T : class, IEntityWithKey
{
int count;
return new List<T>(Find<T>(null, null, 0, 0, out count));
}
public IList<T> Find<T>(Expression<Func<T, bool>> filter, Expression<Func<T, object>> sort)
{
int count;
return new List<T>(Find(filter, sort, 0, 0, out count));
}
public IEnumerable<T> Find<T>(Expression<Func<T, bool>> filter, Expression<Func<T, object>> sort, int pageSize,
int pageNumber, out int count)
{
return ExecuteQuery(filter, sort, pageSize, pageNumber, out count) ?? new T[] {};
}
public bool Save<T>(T entity)
{
var contextSource = new EntityFrameworkContext();
EntitiesContext context = contextSource.Context;
EntityKey key = context.CreateEntityKey(GetEntitySetName(entity.GetType()), entity);
object originalItem;
if (context.TryGetObjectByKey(key, out originalItem))
{
context.ApplyPropertyChanges(key.EntitySetName, entity);
}
else
{
context.AddObject(GetEntitySetName(entity.GetType()), entity);
//Attach(context, entity);
}
return context.SaveChanges() > 0;
}
public bool Delete<T>(Expression<Func<T, bool>> filter)
{
var contextSource = new EntityFrameworkContext();
EntitiesContext context = contextSource.Context;
int numberOfObjectsFound = 0;
foreach (T entity in context.CreateQuery<T>(GetEntitySetName(typeof (T))).Where(filter))
{
context.DeleteObject(entity);
++numberOfObjectsFound;
}
return context.SaveChanges() >= numberOfObjectsFound;
}
#endregion
protected IEnumerable<T> ExecuteQuery<T>(Expression<Func<T, bool>> filter, Expression<Func<T, object>> sort,
int pageSize, int pageNumber,
out int count)
{
IEnumerable<T> result;
var contextSource = new EntityFrameworkContext();
EntitiesContext context = contextSource.Context;
ObjectQuery<T> originalQuery = CreateQuery<T>(context);
IQueryable<T> query = originalQuery;
if (filter != null)
query = query.Where(filter);
if (sort != null)
query = query.OrderBy(sort);
if (pageSize > 0)
{
int pageIndex = pageNumber > 0 ? pageNumber - 1 : 0;
query = query.Skip(pageIndex).Take(pageSize);
count = query.Count();
}
else
count = -1;
result = ExecuteQuery(context, query);
//if no paging total count is count of the entire result set
if (count == -1) count = result.Count();
return result;
}
protected internal event Action<ObjectContext, IEnumerable> EntitiesFound;
protected void OnEntitiesFound<T>(ObjectContext context, params T[] entities)
{
if (EntitiesFound != null && entities != null && entities.Length > 0)
{
EntitiesFound(context, entities);
}
}
//Allowing room for system-specific-requirement extensibility
protected Action<IEnumerable> ItemsFound;
protected IEnumerable<T> ExecuteQuery<T>(ObjectContext context, IQueryable<T> query)
{
IEnumerable<T> result = null;
if (query is ObjectQuery)
{
var objectQuery = (ObjectQuery<T>) query;
objectQuery.EnablePlanCaching = false;
objectQuery.MergeOption = MergeOption.PreserveChanges;
result = new List<T>(objectQuery);
if (ItemsFound != null)
ItemsFound(result);
return result;
}
return result;
}
internal static RelationshipManager GetRelationshipManager(object entity)
{
var entityWithRelationships = entity as IEntityWithRelationships;
if (entityWithRelationships != null)
{
return entityWithRelationships.RelationshipManager;
}
return null;
}
protected ObjectQuery<T> CreateQuery<T>(ObjectContext context)
{
ObjectQuery<T> query = context.CreateQuery<T>(GetEntitySetName(typeof (T)));
query = this.AggregateEntities(query);
return query;
}
protected virtual ObjectQuery<T> AggregateEntities<T>(ObjectQuery<T> query)
{
return query;
}
private static string GetEntitySetName(Type entityType)
{
return string.Format("{0}Set", entityType.Name);
}
}
public class EntityFrameworkContext
{
private const string CtxKey = "ctx";
private bool contextInitialized
{
get { return HttpContext.Current.Items[CtxKey] != null; }
}
public EntitiesContext Context
{
get
{
if (contextInitialized == false)
{
HttpContext.Current.Items[CtxKey] = new EntitiesContext(ConfigurationManager.ConnectionStrings["CoonectionStringName"].ToString());
}
return (EntitiesContext)HttpContext.Current.Items[CtxKey];
}
}
public void TrulyDispose()
{
if (contextInitialized)
{
Context.Dispose();
HttpContext.Current.Items[CtxKey] = null;
}
}
}
internal static class EntityFrameworkExtensions
{
internal static ObjectQuery<T> Include<T>(this ObjectQuery<T> query,
Expression<Func<T, object>> propertyToInclude)
{
string include = string.Join(".", propertyToInclude.Body.ToString().Split('.').Skip(1).ToArray());
const string collectionsLinqProxy = ".First()";
include = include.Replace(collectionsLinqProxy, "");
return query.Include(include);
}
internal static string After(this string original, string search)
{
if (string.IsNullOrEmpty(original))
return string.Empty;
int index = original.IndexOf(search);
return original.Substring(index + search.Length);
}
}
}
在 Conery 的 MVC Storefront 中,他创建了另一个称为“服务”层的层,该层从存储库接收 IQueryable 结果并负责应用各种过滤器。
在所有情况下,除了服务层之外,没有人应该直接与存储库进行交互。
最灵活的事情是让服务以任何他们想要的方式与存储库交互,就像上面的代码一样(但通过一个点 - 就像示例中一样 - 编写 DRY 代码并找到优化的地方)。
但是,就常见的 DDD 模式而言,更正确的方法是使用“规范”模式,将所有过滤器等封装在变量中(类成员,在 LINQ 中通常是委托类型)。当您将 LINQ 与“已编译查询”结合使用时,LINQ 可以从中获得很大的优化优势。如果你用谷歌搜索 {Specification Pattern} 和 {LINQ Compiled Queries},你会更接近我的意思。