db.Database.SqlQuery<int>(
"select sum(QUANTITY) from SomeTable
where USER_ID = :userid and Timestamp >= :someDate1and
and Timestamp < :someDate2",
userId, someDate1, someDate2
)
.First();
这需要 20 毫秒
var cnt = db.SomeTable.Where(x =>
x.User.Id == user.Id
&& x.Timestamp >= someDate1
&& x.Timestamp < someDate2
)
.Sum(x => x.Quantity);
这需要 800 毫秒才能执行
我在代码之前和之后设置了标记,var start = DateTime.UtcNow;
然后我记录了(DateTime.UtcNow - start).TotalMilliseconds
.
如果我检查生成的 SQL 并直接在服务器上执行它需要 2ms。那么 EF 将剩余的 798 毫秒用于什么?取一个号码?
这是生成的SQL
SELECT "GroupBy1"."A1" AS "C1"
FROM
(SELECT SUM("Extent1"."QUANTITY") AS "A1"
FROM "FB"."SomeTable" "Extent1"
WHERE ((("Extent1"."USER_ID" = :p__linq__0)
OR (("Extent1"."USER_ID" IS NULL)
AND (:p__linq__0 IS NULL)))
AND ("Extent1"."TIMESTAMP" >= :p__linq__1)
AND ("Extent1"."TIMESTAMP" < :p__linq__2))
) "GroupBy1";