奇怪的是:实体框架(代码优先)速度较慢,并且与通用存储库一致

时间:2013-05-08 06:24:08

标签: performance generics load ef-code-first repository

我们使用代码优先技术完成了通用存储库。在代码处于测试阶段时,我们意识到通用存储库比直接访问DBContext和加载数据的速度慢。为了模拟大家的问题,我们简化了通用存储库编写的新代码,并将代码粘贴在下面。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DemoTest.Bll.Models;
using DemoTest.Bll.DB;
using MasIt.Common.BackEnd;
using System.Data.Entity;

namespace DemoTest.Bll.Handlers
{
    public abstract class MyHandlerBase<E, T>
        where E : DbSet<T>
        where T : class, IBaseObject
    {
        public MyHandlerBase(E mySet)
        {
            dbSet = mySet;
        }
        public E dbSet;
        protected IEnumerable<T> GetAllNew(Func<T, bool> predicate)
        {
            try
            {
                return dbSet.Where(predicate).AsEnumerable();
            }
            catch { return null;  }
        }

    }

public class StudentHandler : MyHandlerBase<DbSet<Student>, Student>
{
    public StudentHandler()
        :base(DemoDBContext.GetContext().Students)
    {
        //_entitySet = new DemoDBContext().Students;
    }

    public List<Student> getList(bool option1)
    {
        if (option1)
        {
            // Option 1 this is very fast and hit the Student Constructor only once
            IEnumerable<Student> response1 = this.dbSet.Where(x => x.StudentId == 10).AsEnumerable();
            return response1.ToList();
        }
        else
        {
            // Option 2 this is very slow and hit the Student Constructor the student record count of the table
            IEnumerable<Student> response2 = this.GetAllNew(x => x.StudentId == 10);
            return response2.ToList();
        }
    }
}
}

任何人都可以说为什么选项2更慢..它不仅慢,它多次击中Student类构造函数,而选项1只击中构造函数一次..所以在我们看来,选项1仅加载匹配记录,其中选项2加载所有记录并在内存中匹配它们以过滤记录..

Generic Repository是必须的.​​.任何修复都非常受欢迎......

1 个答案:

答案 0 :(得分:2)

得到了修复......

更换 “Func&lt; T,bool&gt;谓词”用 “表达式&lt; Func&lt; E,Boolean&gt;&gt;”谓词做了伎俩..

男人..一场可怕的噩梦刚刚结束......