【问题标题】:How to retrive distinct rows based on a column when join in entity framework?加入实体框架时如何根据列检索不同的行?
【发布时间】:2019-05-02 06:10:01
【问题描述】:

我想加入 2 个表并根据实体框架中的 2 列检索不同的行。

我已经阅读了网络上的帖子,包括 SO。

在下面的代码中,
1. 我根据CurrentTurnID 键加入 2 个表
2. 我按我想要的功能过滤表格
3. 我通过对所选特征设置条件来过滤表格
4. 我选择一列来计算它的所有值的总和

我只需要检索一次具有相同CurrentTurnID 的记录。这是我的代码:

int services = Convert.ToInt32(database.Tbl_CurrentTurn.AsNoTracking()
            .Join(database.Tbl_pay.AsNoTracking(), f => f.CurrentTurnID,
               s => s.CurrentTurnID, (f, s) => new
               {
                   f.CurrentTurnOfficialID,
                   f.CurrentTurnID,
                   f.SickID,
                   f.Remove,
                   f.Payment,
                   f.ServicePayment,
                   s.isDeposit
               })
            .Where(w => w.SickID == SickId && w.Remove != true && w.Payment == true && w.isDeposit != true)
            .Select(s => s.ServicePayment).DefaultIfEmpty(0).Sum());

如果我在Select() 语句之后添加Distinct(),它会考虑使用ServicePayment 来过滤不同的行。

更新: The Image is attached to my Dropbox. 第 2 条和第 3 条记录具有相同的 CurrentTurnID 值。所以我想只考虑其中之一。然后总结ServicePayment 列上的记录。请注意,这 2 条记录中的其他列是不同的。

【问题讨论】:

  • 您是否也尝试过使用 GroupBy?
  • 我应该如何使用GroupBy?我无法做出适当的聚合函数。
  • 澄清一下,您想总结ServicePaymant 上具有相同CurrentTurnID 的所有记录?
  • 不,我想对所有行中的ServicePayment 列求和,但只考虑一次具有相同CurrentTurnID 的行。
  • 您是否因为连接条件错误而获得“重复”行?

标签: c# entity-framework join


【解决方案1】:

您可以尝试GroupJoin 来获取该信息,而无需像这样使用Distinct

int services = Convert.ToInt32(database.Tbl_CurrentTurn.AsNoTracking()
        .GroupJoin(database.Tbl_pay.AsNoTracking(), f => f.CurrentTurnID,
           s => s.CurrentTurnID, (f, s) => new {f, s})
         .SelectMany(x=> x.s.DefaultIfEmpty(), (f, s) => new
           {
               f.CurrentTurnOfficialID,
               f.CurrentTurnID,
               f.SickID,
               f.Remove,
               f.Payment,
               ServicePayment = s != null ? s.ServicePayment : 0,
               s.isDeposit
           })
        .Where(w => w.SickID == SickId && w.Remove != true && w.Payment == true 
               && w.isDeposit != true)
        .Select(x=> x.ServicePayment).Sum());

这可能无法正确编译,因为我没有所有变量和一个可以用来测试它的小示例。

您应该能够通过很少的更改使其工作。我使用类似的查询来获取成本报告列表。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-24
    • 2011-07-09
    • 1970-01-01
    相关资源
    最近更新 更多