C# 如何在Linq to Sql代码中修复此Count语句?

C# 如何在Linq to Sql代码中修复此Count语句?,c#,linq-to-sql,C#,Linq To Sql,我有以下Linq到SQL查询。在第5行,我试图从满足where语句中列出的条件的Packages表中获取记录数。我认为除了第5行之外,这段代码中的所有内容都是正确的。我做错了什么 var Overage = from s in db.Subscriptions join p in db.Packages on s.UserID equals p.UserID where s.SubscriptionType != "PayAsYouGo" &&

我有以下Linq到SQL查询。在第5行,我试图从满足where语句中列出的条件的Packages表中获取记录数。我认为除了第5行之外,这段代码中的所有内容都是正确的。我做错了什么

var Overage = from s in db.Subscriptions
    join p in db.Packages on s.UserID equals p.UserID
    where 
      s.SubscriptionType != "PayAsYouGo" && 
      (s.CancelDate == null || s.CancelDate >= day) && 
      s.StartDate <= day && p.DateReceived <= day && 
      (p.DateShipped == null || p.DateShipped >= day)
    let AverageBoxSize = (p.Height * p.Length * p.Width) / 1728
    let ActiveBoxCount = p.Count()
    select new
    {
      p,
      AverageBoxSize,
      ActiveBoxCount,
      s.Boxes
    };
Box是每个用户在其订阅下允许的最大数量

包装表

UserID | PackageID | Height | Length | Width
001      00001       10       10       10
001      00002       10       10       10
001      00003       20       10       10
003      00004       10       20       20
003      00005       10       10       10
所需的查询结果

UserID | Boxes | Box Count | Average Box Size
001      5           3           1,333
003      5           2           2,500

用户002未出现,因为Where子句排除了该用户

p不是集合。它应该是:让ActiveBoxCount=db.Packages.Count()

根据您对Ryan答案的评论,这可能是您想要的:

var Overage = from s in db.Subscriptions
    join p in db.Packages on s.UserID equals p.UserID
    where 
      s.SubscriptionType != "PayAsYouGo" && 
      (s.CancelDate == null || s.CancelDate >= day) && 
      s.StartDate <= day && p.DateReceived <= day && 
      (p.DateShipped == null || p.DateShipped >= day)
    select new
    {
      p,
      AverageBoxSize = (p.Height * p.Length * p.Width) / 1728,
      ActiveBoxCount = db.Packages.Where(x => x.UserID == p.UserID).Count(),
      s.Boxes
    }
var Overage=来自数据库订阅中的
在s.UserID等于p.UserID的db.Packages中加入p
哪里
s、 订阅类型!=“Payasougo”和
(s.CancelDate==null | | s.CancelDate>=天)和
s、 StartDate x.UserID==p.UserID).Count(),
s、 盒子
}

可能最容易的方法是将您的Let line替换为-

Group <columns> By UserId into summary = Group 
Aggregate x in summary Into ActiveBoxCount = x.Count
Group By UserId into summary=Group
将汇总中的x聚合为ActiveBoxCount=x.Count

是的,你做错了什么?是否有错误?运行此操作会产生什么结果?它是否会产生一个错误,0,1?很抱歉。我忘了把错误信息的文本放在我的问题中。现在已修复。P是包对象的实例,而不是collection@Ryan. 谢谢我需要的计数实际上是每个用户ID。但是db.Packages.Count()会给出所有用户的总计数,对吗?@Magnus想得不错,但这行不通。s、 Boxes告诉我根据订阅表允许用户拥有的最大盒数。我试图根据packages表计算每个用户实际拥有的数量。在阅读各种注释时,我认为我的错误在于我需要按UserID对结果进行分组。你的ActiveBoxCount产品线就是这样做的吗?如果是这样的话,我还需要修正我的平均尺寸公式,这样它就可以求出尺寸的乘积。我可能无法选择“p”而不聚合p的所有其他列(这是可以的,因为我不再需要p)。在这种情况下,您需要对当前返回的所有属性进行分组,我不确定在
s.box
集合中是否可以这样做
Group <columns> By UserId into summary = Group 
Aggregate x in summary Into ActiveBoxCount = x.Count