一个VEW的事情我经常这样做:
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
条款,你可以。我试图找到第二个片段比第一更易读:
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)防止,如果你能加入。 LINQ to SQL通常允许您在不使用难以理解的join
语句的情况下对所有父子关系进行“点”化。
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;
}
不要忘记标记您最喜欢的答案。 NetSide的答案将是一个很好的候选人。 – Steven 2010-11-23 20:19:32