Func<Invoice, bool> func = x => x.State == InvoiceState.Created; Expression<Func<Invoice, bool>> expression = x => x.State == InvoiceState.Created; using (var db = new CrmDbContext()) { var q1 = db.Invoices.Where(func); //全部查询出来后筛选 var q2 = db.Invoices.Where(expression); //直接延迟到Count时执行 var query = db.Invoices.AsQueryable(); var qq1 = query.Where(func);//全部查询出来后筛选 var qq2 = query.Where(expression); //直接延迟到Count时执行 Console.WriteLine($"q1:{q1.Count()}"); Console.WriteLine($"q2:{q2.Count()}"); Console.WriteLine($"qq1:{qq1.Count()}"); Console.WriteLine($"qq2:{qq2.Count()}"); }
看到上面的不同表现结果,知道该怎么写了吧!
简单来说:委托的查询是针对一个(已存在的)集合的,而表达式是用来表述条件。