我尝试使用Except方法。我认为这个方法比WHERE子句更强大并且生成一个更干净的SQL但不是。它生成相同的sql。
为什么/何时使用Except方法?
编辑:这是一个示例:
// Get customers except those which ID are in the LostCustomers table
TblCustomers.Except(TblCustomers.Where(tj => LostCustomers.Select(lj => lj.CustomerId).Contains(tj.CustomerID))).Select(j => new
{
CustomerId = j.CustomerID,
CustomerRef = j.CustomerRef,
CustomerName = j.Name
})
// Get customers except those which ID are in the LostCustomers table
TblCustomers.Where(tj => !LostCustomers.Select(lj => lj.CustomerId).Contains(tj.CustomerID)).Select(j => new
{
CustomerId = j.CustomerID,
CustomerRef = j.CustomerRef,
CustomerName = j.Name
})
THX
答案 0 :(得分:0)
根据您认为会生成的SQL,选择LINQ模式很少值得。相反,使用任何方法似乎给你最清晰的代码。例如,我认为在这种情况下,除了更清楚:
var taskIds = db.Tasks.Select(task => task.Id);
var doneTaskIds = db.TaskCompletions.Select(tc => tc.TaskId);
var unfinishedTaskIds = taskIds.Except(doneTaskIds);
而不是:
var unfinishedTaskIds = taskIds.Where(id => !doneTaskIds.Contains(id));
但是很多很多情况下Where()
更有意义。在上面的例子中,你可以这么说,这可能会更清楚:
var unfinishedTasks = db.Tasks.Where(task => !task.TaskCompletions.Any());