我是EF的新手,我正在尝试一些非常基本的东西。在一个全新的控制台应用程序项目中,我只使用了"反向工程师代码优先" (来自Entity Framework Power Tools)在db(本地到我的机器上)。
然后我修改了Main以进行一些基本测试...从一个表中读取相同的三行两次...一次使用EF,一次使用传统系统(SqlConnection,DataReader等)我计时两个系统,并以微秒为单位打印输出时间。
当它运行时,我得到以下内容(当然略有变化):
EF query 1: 5540 (slow, but startup...perhaps expected.)
EF query 2: 907 (What? Why so slow?)
EF query 3: 910
Trad query 1: 0 (Fast, even though I'm creating a new connection each time)
Trad query 2: 0
Trad query 3: 0
我做错了什么吗?我的LINQ查询是否在某种程度上搞砸了并且无可救药地效率低下,或者EF出于某种原因真的很慢?
代码:
static void Main(string[] args)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
// EF Path
// Selecting three rows, one at a time
using (var context = new myCustomContext())
{
var query = from b in context.myTable
where b.KEY == "Key1"
select b;
stopwatch.Stop();
foreach (var returnedVal in query)
{
Console.WriteLine("EF query 1: " + stopwatch.ElapsedMilliseconds);
}
stopwatch.Restart();
var query2 = from b in context.myTable
where b.KEY == "Key2"
select b;
foreach (var returnedVal in query2)
{
Console.WriteLine("EF query 2: " + stopwatch.ElapsedMilliseconds);
}
stopwatch.Restart();
var query3 = from b in context.myTable
where b.KEY == "Key3"
select b;
foreach (var returnedVal in query3)
{
Console.WriteLine("EF query 3: " + stopwatch.ElapsedMilliseconds);
}
}
// Traditional path
// Selecting same three rows, one at a time. I recreate a connection
// each time, in a futile attempt to even the odds.
string connectionString = "<myConnectionString>";
stopwatch.Restart();
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
using (SqlCommand command = new SqlCommand("select * from myTable where KEY = 'Key1'", con))
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine("Trad query 1: " + stopwatch.ElapsedMilliseconds);
}
}
}
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
stopwatch.Restart();
using (SqlCommand command = new SqlCommand("select * from myTable where KEY = 'Key2'", con))
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine("Trad query 2: " + stopwatch.ElapsedMilliseconds);
}
}
stopwatch.Restart();
}
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
using (SqlCommand command = new SqlCommand("select * from myTable where KEY = 'Key3'", con))
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine("Trad query 3: " + stopwatch.ElapsedMilliseconds);
}
}
}
Console.ReadLine();
}