我对编写linq查询的常见做法有疑问。其实我跟同事有争执。
我们有一个布尔变量,如果它是真的 - 需要额外的检查。万一它是假的,应该没有这样的检查。
在linq中有两种方法可以实现它:
bool onlyForReturningCustomers;
.....
return context.Products.Where(product => product.StartTime >= fromDate
&& product.StartTime < toDate
&& (onlyForReturningCustomers ? product.IsReturningClient : true));
和第二个:
bool onlyForReturningCustomers;
.....
var q = context.Products.Where(product => product.StartTime >= fromDate && product.StartTime < toDate);
if (onlyForReturningCustomers) {
q = q.Where(product => product.IsReturningClient);
}
return q;
第一个在sql中呈现case
语句,当onlyForReturningCustomers=false
出现1=1
之类的语句时,会更容易阅读此代码。
第二个不是那么容易阅读但它在没有任何垃圾的情况下在sql中呈现清晰的语句。
你会使用哪一个?
答案 0 :(得分:4)
如果您将来为返回的客户或其他类型的客户添加业务规则,则第二个语句更易于阅读,也更易于维护。
答案 1 :(得分:3)
我可能会去
bool onlyForReturningCustomers;
.....
// Make a positively-named variable
bool includeAllCustomers = !onlyForReturningCustomers;
var q = context.Products.Where(product => product.StartTime >= fromDate
&& product.StartTime < toDate
&& (includeAllCustomers
|| product.IsReturningClient));
return q;
这与你的第一种方式基本相同,但没有条件表达式的奇怪性,其中一个分支只是说true
。
答案 2 :(得分:0)
我会使用第一个,因为看起来第二个选项实际上是数据的两次往返。
我还会复制LINQ语句发出的SQL,将其粘贴到您喜欢的SQL工具(例如SQL Server Management Studio)中,在SET STATISTICS IO ON
上方添加SELECT
声明并检查执行查询所需的逻辑读取(越低越好)。