【问题标题】:Subsonic 3 and Linq Group by with CountSubsonic 3 和 Linq Group by with Count
【发布时间】:2009-08-27 12:11:18
【问题描述】:

我有以下两张表:

Customer
{
int Id
int Name
}

Bills
{
int Id
int CustomerId
decimal Amount
bool IsDue
}

现在我正在尝试获取我拥有的列表:

  1. 为每位客户提供一个条目,其中包含相关账单的计数。
  2. 每个客户的条目,其中包含 IsDue 为 true 的相关帐单计数。

我尝试像这样做第一个:

var results = from c in _db.Customers
              join b in _db.Bills on c.Id equals b.CustomerId into j1
              from j2 in j1
              group j2 by c.Id into grouped
              select new
                  {
                      CustomerId = grouped.Key, 
                      NoOfBills = grouped.Count()
                  };

这是抛出一个错误: 'System.Collections.Generic.IEnumerable1[OutstandingMonitor.MonitorData.Customer]' cannot be used for parameter of type 'System.Linq.IQueryable1[OutstandingMonitor.MonitorData.Customer]' 类型的表达式 ...

请帮我解决这个问题。

另外,这两个查询可以合并吗?

PS:使用带有 ActiveRecord 的 Subsonic 3.0.0.3

【问题讨论】:

    标签: c# linq subsonic subsonic3


    【解决方案1】:

    我找到了一个不太有效的解决方案(如果它确实有效,我很想知道......:P)。这里是:

    var results = from d in _db.Bills
              group d by d.CustomerId into g
              select new
              {
                  CustomerId = g.Key,
                  NoOfBills = g.Count()
              };
    
    var results2 = from c in _db.Customers
               join r in results on c.Id equals r.CustomerId
               select new
               {
                   CustomerId = r.CustomerId,
                   CustomerName = c.Name,
                   City = c.City,
                   NoOfBills = r.NoOfBills
               };
    

    暂时还不错。

    【讨论】:

      【解决方案2】:

      无论您在何处使用“客户的相关账单计数”的值,您都不能简单地在 LINQ 中执行此操作(但是,如果您在 DBML 中设置了适当的关系,这将起作用):

      var customers = _db.Customers; // Not necessary, but here for clarity
      
      // ... more code
      
      // Access the number of bills for each customer:
      
      foreach (var customer in customers)
      {
          int totalBills = customers.Bills.Count();
          int totalDueBills customers.Bills.Where(b => b.IsDue).Count();
      }
      

      【讨论】:

      • 我认为您指的是 LINQ to SQL,而他正在使用 SubSonic。
      • 是的。我正在使用 SQLite。有没有办法用 SubSonic 和 SQLite 生成外键关系?
      • @John - 正确,我为假设 LINQ-to-SQL 道歉,但我很惊讶无法完成类似的事情。
      • 我使用 PRAGMA foreign_key_list 管理外键关系生成。但这仍然无助于我的事业。这是 SubSonic 中的错误吗?
      猜你喜欢
      • 1970-01-01
      • 2014-05-20
      • 1970-01-01
      • 2020-10-30
      • 2020-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多