[英]Adding WHERE statements to a LINQ lambda expression
The two tables I'm working with here are built like this: 我在这里使用的两个表是这样构建的:
Users Table PurchaseLog Table
ID| LDAP| FNAME| LNAME| ID| UserID| PurchaseID | LOCATION |TIME
I'm trying to build a query that gets me back each user and the number of purchases they have. 我正在尝试构建一个查询,让我回复每个用户以及他们拥有的购买数量。 The model I'm trying to fill:
我试图填写的模型:
public class UserPurchaseCount{
public string LDAP {get; set;}
public int Count {get; set;}
}
This SQL query I wrote appears to be returning the correct results, 我写的这个SQL查询似乎返回了正确的结果,
Select Users.LDAP, count(*) as Purchases
FROM Users
JOIN PurchaseLog ON PurchaseLog.UserId=Users.ID
WHERE Users.FName NOT LIKE '%name%'
AND PurchaseLog.CreatedDate <= 'some end date'
AND Purchase.CreatedDate >= 'some start date'
GROUP BY Users.LDAP
I suck at lambdas, but I like them and want to get a better understanding of them. 我很讨厌lambdas,但我喜欢它们,希望能更好地理解它们。 Here's what I've got so far:
这是我到目前为止所得到的:
var items = db.PurchaseLogs
.Join(db.Users, usr => usr.UserId, x => x.ID, (usr, x) => new { usr, x })
.GroupBy(y => new { y.x.LDAP})
//.Where(i => i.CreatedDate >= startDate)
//.Where(i => i.CreatedDate <= endDate)
//.Where(i => i.FName.Contains("Guy1", StringComparison.CurrentCultureIgnoreCase) == false)
.Select(g => new
{
g.Key.LDAP,
Count = g.Count()
})
.ToList();
This lambda expression works. 这个lambda表达式有效。 When I uncomment the WHERE clauses, the compiler throws up in my face.
当我取消注释WHERE子句时,编译器会抛出我的脸。
Error 6 'System.Linq.IGrouping<AnonymousType#2,AnonymousType#3>' does not contain a definition for 'FName'...
Don't group before apply the conditions: 在申请条件之前不要分组:
var items =db.PurchaseLogs
.Join(db.Users, usr => usr.UserId, x => x.ID, (usr, x) => new { usr, x })
.Where(i => i.user.CreatedDate >= startDate)
.Where(i => i.user.CreatedDate <= endDate)
.Where(i => !i.x.FName.Contains("Guy1"))
.GroupBy(y => new { y.x.LDAP})
.Select(g => new
{
g.Key.LDAP,
Count = g.Count()
})
.ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.