私がよくすること:
1)レイアウト:常に次の行からクエリを開始します。例:これを行わないでください
var allCustomersThatDontContainUnpayedOrders = from customer in db.Customers
where customer.Orders ...
select customer;
しかし、これを行います:
var allCustomersThatDontContainUnpayedOrders =
from customer in db.Customers
where customer.Orders ...
select customer;
2)where
可能な場合は複数の句を使用します。最初のスニペットよりも読みやすい2番目のスニペットを見つけようとしています。
var results =
from customer in db.Customers
where customer.Name.Contains(search) && customer.Address.City != null &&
customer.Employee.IsSenior
select customer;
var results =
from customer in db.Customers
where customer.Name.Contains(search)
where customer.Address.City != null
where customer.Employee.IsSenior
select customer;
3)可能であれば、参加を防止します。join
LINQ to SQLを使用すると、理解しにくいステートメントを使用せずに、すべての親子関係に「ドット」を付けることができます。
4)多くの場合、多くのクエリが似ていることがわかります。ユーザーの権限に基づいて特定のレコードを常にフィルタリングしたい場合があります。次のメソッドでこのコードを抽出できます。
var customers = db.Customers;
customers = FilterBasedOnUserRights(customers, currentUser);
public static IQueryable<Customer> FilterBasedOnUserRights(
IQueryable<Customers customers, User currentUser)
{
return
from customer in customers
where [big complicated where clause]
select customer;
}