我是新手使用ORM处理数据库,目前我正在制作一个新项目,我必须决定是否使用Entity Framework或Dapper.我读了许多文章说Dapper比实体框架更快.
所以我使用Dapper创建了两个简单的原型项目,另一个使用Entity Framework和一个函数从一个表中获取所有行.表格架构如下图所示

以及两个项目的代码如下
对于Dapper项目
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
sw.Start();
IEnumerable<Emp> emplist = cn.Query<Emp>(@"Select * From Employees");
sw.Stop();
MessageBox.Show(sw.ElapsedMilliseconds.ToString());
Run Code Online (Sandbox Code Playgroud)
实体框架项目
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
sw.Start();
IEnumerable<Employee> emplist = hrctx.Employees.ToList();
sw.Stop();
MessageBox.Show(sw.ElapsedMilliseconds.ToString());
Run Code Online (Sandbox Code Playgroud)
经过多次尝试上面的代码只有我第一次运行项目时,dapper代码会更快,在这第一次之后我总是从实体框架项目中获得更好的结果我还尝试了以下关于实体框架项目的语句来阻止懒惰装载
hrctx.Configuration.LazyLoadingEnabled = false;
Run Code Online (Sandbox Code Playgroud)
但是,除了第一次以外,EF的表现仍然相同.
虽然网上的所有文章都相反,但任何人都能给我解释或指导EF在这个样本中的速度更快
更新
我已经改变了实体样本中的代码行
IEnumerable<Employee> emplist = hrctx.Employees.AsNoTracking().ToList();
Run Code Online (Sandbox Code Playgroud)
使用某些文章中提到的AsNoTracking会停止实体框架缓存,停止缓存后,dapper样本表现更好,(但不是很大的区别)
我研究了Dapper和ADO.NET,并对两者进行了选择测试,发现有时ADO.NET比Dapper更快,有时会逆转.我知道这可能是数据库问题,因为我正在使用SQL Server.据说反射很慢,我在ADO.NET中使用反射.那么有谁能告诉我哪种方法最快?
这是我编码的.
使用ADO.NET
DashboardResponseModel dashResp = null;
SqlConnection conn = new SqlConnection(connStr);
try
{
SqlCommand cmd = new SqlCommand("spGetMerchantDashboard", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@MID", mid);
conn.Open();
var dr = cmd.ExecuteReader();
List<MerchantProduct> lstMerProd = dr.MapToList<MerchantProduct>();
List<MerchantPayment> lstMerPay = dr.MapToList<MerchantPayment>();
if (lstMerProd != null || lstMerPay != null)
{
dashResp = new DashboardResponseModel();
dashResp.MerchantProduct = lstMerProd == null ? new
List<MerchantProduct>() : lstMerProd;
dashResp.MerchantPayment = lstMerPay == null ? new
List<MerchantPayment>() : lstMerPay;
}
dr.Close();
}
return dashResp;
Run Code Online (Sandbox Code Playgroud)使用Dapper
DashboardResponseModel dashResp …Run Code Online (Sandbox Code Playgroud)