实体框架5.x 6.x缓存框架

时间:2013-12-02 09:49:20

标签: c# entity-framework caching redis memcached

我在当前项目中使用EF5,我将其升级到EF6。我知道EF有一个内部查询缓存。这一切都很好,但我认为它不足以满足我的需求。我想使用像memcache或redis这样的缓存服务器。我知道Nhibernate有一些非常好的appender,比如memcache。我发现NCache有一个快速的互联网搜索。但它的文档和样本似乎已经过时了。所以我不确定我是否可以使用它。 EF5或EF6是否有稳定的缓存提供程序?

4 个答案:

答案 0 :(得分:2)

尝试使用您喜欢的任何缓存机制的EntityFramework.Extended缓存。

https://github.com/loresoft/EntityFramework.Extended/wiki/Query-Result-Cache

答案 1 :(得分:2)

EF6.1还没有稳定的缓存提供程序,但你可以看看

Second Level Cache for EF 6.1 | Code, the Universe and everything

答案 2 :(得分:1)

您无法开箱即用。 EF6不支持二级缓存。

您必须为数据库操作实现一个包装类。

示例:

public abstract class BaseEntity{ public int Id { get;set; }

public interface IRepository<T> where T : BaseEntity
{

    T GetById(object id);
    void Insert(T entity);
    void Update(T entity);
    void Delete(T entity);
    IQueryable<T> Table { get; }
}

public class EfRepository<T> : IRepository<T> where T : BaseEntity
{
    private readonly IDbContext _context;
    private IDbSet<T> _entities;


    public EfRepository(IDbContext context)
    {
        this._context = context;
    }

    public virtual T GetById(object id)
    {
        //Check cache first, if exists 
        return this.Entities.Find(id);
    }

    public virtual void Insert(T entity)
    {

        if (entity == null)
                throw new ArgumentNullException("entity");


         this.Entities.Add(entity);
         //Add entity to cache
         this._context.SaveChanges();

    }

    public virtual void Update(T entity)
    {
        //Update cache
            if (entity == null)
                throw new ArgumentNullException("entity");

            this._context.SaveChanges();

    }

    public virtual void Delete(T entity)
    {
        //Remove from cache
        this.Entities.Remove(entity);
        this._context.SaveChanges();

    }

    public virtual IQueryable<T> Table
    {
        get
        {
            return this.Entities;
        }
    }

    protected virtual IDbSet<T> Entities
    {
        get
        {
            if (_entities == null)
                _entities = _context.Set<T>();
            return _entities;
        }
    }
}

git hub here上还有一些缓存提供程序,以及一个基于here的redis提供程序。

答案 3 :(得分:0)

Microsoft enterprise library caching block值得一看。

可通过nuget Install-Package EnterpriseLibrary.Caching

获取

caching block Documentation

Caching Architecture Guide for .NET Framework Applications