利用UnitOfWork与SqlDependency和Memory Cache

时间:2016-06-15 20:54:27

标签: c# entity-framework caching

我已成功合并了我的UnitOfWork模式以获得SqlDependency。这意味着我发送到数据库的任何查询,如果有任何更改,则发送通知。

public override IEnumerable<T> Get(Expression<Func<T, bool>> filter = null,
    Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null,
    int? numberOfEntities = null,
    IEnumerable<string> includeProperties = null)
{

    IQueryable<T> query = DbSet;

    if (filter != null)
    {
        query = query.Where(filter);
    }

    if (includeProperties != null)
    {
        query = includeProperties.Aggregate(query,
            (current, includeProperty) => current.Include(includeProperty));
    }

    if (orderBy != null)
    {
        query = orderBy(query);
    }

    var actualNumberOfEntities = int.MaxValue;

    if (numberOfEntities.HasValue)
    {
        actualNumberOfEntities = Math.Max(1, numberOfEntities.Value);
    }

    notification = new ImmediateNotificationRegister<T>(Context, query);
    notification.OnChanged += NotificationOnChanged;
    return query.AsExpandable().Take(actualNumberOfEntities).ToList();
}

我想将集合保存到内存缓存中,但我不确定如何在通用级别执行此操作并且仍然会过滤集合(如果已过滤)。如果我想拥有everyitem,我可以使用以下方法,但我想知道我是否可以保存单个实体或过滤集合

public void ClearCache()
{
    MemoryCache.Default.Remove(MemoryCacheNameGetAll);
}

public void SetCache()
{
    if (MemoryCache.Default[MemoryCacheNameGetAll] == null)
        MemoryCache.Default[MemoryCacheNameGetAll] =
                Context.Set<T>().ToList();
}

public IEnumerable<T> GetAll()
{
    SetCache();
    return MemoryCache.Default[MemoryCacheNameGetAll]
        as IEnumerable<T>;
}

0 个答案:

没有答案