1

我们有一个使用代码优先技术完成的通用存储库。由于代码在测试中,我们意识到通用存储库比直接访问 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加载所有记录并在内存中匹配它们以过滤记录..

通用存储库是必须的.​​.....任何修复都非常感谢......

4

1 回答 1

2

得到修复...

将“Func<T, bool> 谓词”替换为“Expression<Func<E, Boolean>>”谓词就可以了。

伙计..一场可怕的噩梦刚刚结束..

于 2013-05-08T06:48:59.290 回答