我有一个存储库接口,如下所示:
public interface IDataContext<TId> : IDisposable
{
IQueryable<T> Repository<T>() where T : class, IEntity<TId>;
T FindById<T>(TId id) where T : class, IEntity<TId>;
void Insert<T>(T item) where T : class, IEntity<TId>;
void Delete<T>(T item) where T : class, IEntity<TId>;
void Commit();
}
请注意,Repository<T>
返回一个IQueryable<T>
.
我有一个可以包装 LinqToSQL 数据上下文的类,Repository<T>
方法如下:
public IQueryable<T> Repository<T>() where T : class, IEntity<int>
{
ITable table = _context.GetTable(GetEntityType<T>());
return table.Cast<T>();
}
这很好用,我可以做类似的事情
new Repository(new SQLDataContext())
.Repository<MyEntity>().Where(e => SqlMethods.Like(e.Id, "123%");
现在我已经开始考虑缓存,但我有一个问题。
我创建了一个类,它包装并实现了一个IDataContext<TId>
将调用结果缓存到Repository<T>
内存中的类。如下所示:
public IQueryable<T> Repository<T>() where T : class, IEntity<TId>
{
// Actual caching logic here.....
return _CachedEntities[typeof(T)].OfType<T>().AsQueryable<T>();
}
我遇到的问题是,现在IQueryable<T>
我返回的是内存中,没有翻译成 SQL,所以我得到了一个关于 using 的异常SqlMethods.Like
。
TL;DR:那么,我如何创建我的缓存存储库包装器,使得调用类不需要担心IDataContext<T>
它处理的是内存存储库(即缓存存储库)还是普通的 LinqToSQL存储库?