Linq to SQL 检索单个记录的最快方法

本文关键字:方法 记录 单个 to SQL 检索 Linq | 更新日期: 2023-09-27 18:36:03

以下两个查询之间是否有任何性能差异?

CustomerProduct customerProduct = db.CustomerProducts.SingleOrDefault(p => object.Equals(p.Customer, this));
CustomerProduct customerProduct = (from p in db.CustomerProducts where object.Equals(p.Customer, this) select p).SingleOrDefault();

也许还有另一个,甚至更快?

Linq to SQL 检索单个记录的最快方法

在编译方面,它们应该编译成相同的代码;Linq 只是编译器将为您解释的语法糖。 话虽如此,并非所有 linq 查询都将按照您期望的方式编译,无论如何,都应始终使用 ObjectQuery 强制转换 + ToTraceString 方法检查生成的 sql。