我有一个包含许多层(视图、模型、数据访问、业务)的 MVC 项目,并且我在我的 DataAccessLayer 中使用 GenericDataRepository。我想用 CompiledQueries 增强 GenericDataRepository 的性能。
这是我的 GenericDataRepository,它只有一个功能来保持简单......
public class GenericDataRepository<T> : IGenericDataRepository<T> where T : class
{
public List<T> Get(Expression<Func<T, bool>> filter = null, Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null, params Expression<Func<T, object>>[] includes)
{
IQueryable<T> query = null;
using (var context = new ZenHaberDBEntities())
{
query = context.Set<T>();
foreach (Expression<Func<T, object>> include in includes)
query = query.Include(include);
if (filter != null)
query = query.Where(filter);
if (orderBy != null)
query = orderBy(query);
return query.ToList();
}
}
这是 BusinessLayer 中使用 GenericDataRepository 从数据库中提取数据的代码。
public IList<Article> GetAllArticles()
{
return _articleRepository.Get();
}
我可以将 GetAllArticles() 函数添加到 CompiledQueries 吗?有没有人有这方面的经验?
这是我的上下文
public partial class ZenHaberDBEntities : DbContext
{
public ZenHaberDBEntities()
: base("name=ZenHaberDBEntities")
{
this.Configuration.LazyLoadingEnabled = false;
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<Article> Article { get; set; }
public virtual DbSet<ArticleMedia> ArticleMedia { get; set; }
public virtual DbSet<ArticleTagRelation> ArticleTagRelation { get; set; }
public virtual DbSet<Category> Category { get; set; }
public virtual DbSet<Currency> Currency { get; set; }
public virtual DbSet<Tag> Tag { get; set; }
public virtual DbSet<Weather> Weather { get; set; }
}
public static class DbContextExtensions
{
public static ObjectContext ToObjectContext(this DbContext dbContext)
{
return (dbContext as IObjectContextAdapter).ObjectContext;
}
}