Performance 奇怪:实体框架(代码优先)速度较慢,在通用存储库中表现得非常糟糕
我们使用代码优先技术创建了一个通用存储库。由于代码正在测试中,我们意识到通用存储库比直接访问DBContext和加载数据要慢。为了为大家模拟这个问题,我们简化了通用存储库,编写了一个新代码,该代码粘贴在下面Performance 奇怪:实体框架(代码优先)速度较慢,在通用存储库中表现得非常糟糕,performance,generics,load,ef-code-first,repository,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 MasI
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();
}
}
}
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用demost.Bll.Models;
使用demost.Bll.DB;
使用MasIt.Common.BackEnd;
使用System.Data.Entity;
命名空间demost.Bll.Handlers
{
公共抽象类MyHandlerBase
其中E:DbSet
其中T:class,IBaseObject
{
公共MyHandlerBase(E mySet)
{
dbSet=mySet;
}
公共E数据库集;
受保护的IEnumerable GetAllNew(Func谓词)
{
尝试
{
返回dbSet.Where(谓词).AsEnumerable();
}
catch{return null;}
}
}
公共班级学生管理员:MyHandlerBase
{
公共学生管理者()
:base(DemobContext.GetContext().Students)
{
//_entitySet=新建DemobContext()。学生;
}
公共列表getList(布尔选项1)
{
如果(选项1)
{
//选项1这非常快,只需点击学生构造函数一次
IEnumerable response1=this.dbSet.Where(x=>x.StudentId==10).AsEnumerable();
返回响应1.ToList();
}
其他的
{
//选项2速度非常慢,请点击学生构造函数以获取表的学生记录计数
IEnumerable response2=this.GetAllNew(x=>x.StudentId==10);
返回响应2.ToList();
}
}
}
}
有人能说为什么选项2慢一些吗。。它不仅速度慢,而且多次命中学生类构造函数,而选项1只命中构造函数一次。。因此,在我们看来,选项1只加载匹配的记录,而选项2加载所有记录并在内存中匹配它们以过滤记录
通用存储库是必须的。。非常感谢任何修复…得到修复
替换
“Func谓词”与
“表达式”谓词起了作用
男人。。一场可怕的噩梦刚刚结束