【问题标题】:EF Core Linq Join with OR condition using Method Systax [duplicate]EF Core Linq 使用方法系统税加入 OR 条件 [重复]
【发布时间】:2018-12-11 15:32:16
【问题描述】:

我怎样才能把它变成一个查询?

var result1 = await _dbContext.Emails.Join(_dbContext.Sms,
                                    pn => pn.PNID,
                                    sms => sms.From_PNID.Value,
                                    (pn, sms) => new { sms, pn });


var resut2 = await _dbContext.Emails.Join(_dbContext.Sms,
                                    pn => pn.PNID,
                                    sms => sms.To_PNID.Value,
                                    (pn, sms) => new { sms, pn });

想点赞pn.PNID == sms.To_PNID OR pn.PNID == sms.From_PNID

【问题讨论】:

    标签: c# .net linq entity-framework-core


    【解决方案1】:

    你可以尝试使用SelectMany扩展方法:

    var result1 = await  dbContext.Emails
                        .SelectMany(e=>dbContext.Sms.Where(s=>e.PNID==From_PNID.Value 
                                                           || e.PNID==To_PNID.Value)
                                                    .Select(e=>new {Email=e,SMS=s})).ToListAsync();
    

    【讨论】:

    • 感谢 octavioccl,像魔术一样工作
    • 完美!!很高兴知道;)
    【解决方案2】:

    带有 OR 条件的 LINQ 内连接示例::

                 var q= await  dbContext.Emails
                 .SelectMany(e=>dbContext.Sms.Where(s=>e.PNID==From_PNID.Value 
                                        || e.PNID==To_PNID.Value)
                                        .Select(e=>new {Email=e,SMS=s})).ToListAsync();
    

    试试这个例子!!

    【讨论】:

      【解决方案3】:

      您可以使用传统的 LINQ 代替 LINQ 表达式。

      例如

           var records = (from recordA in TableA 
                          from recordB in TableB 
                          where recordA.Column_1 == recordB.Column_1 || recordA.Column_2 == recordB.Column_2
                         ).ToList();
      

      【讨论】:

      • 我的团队想使用方法表达式而不是查询表达式。
      • 这个查询会生成一个sql交叉连接
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-06
      • 2019-12-17
      • 1970-01-01
      • 2020-03-19
      • 2021-12-09
      • 1970-01-01
      相关资源
      最近更新 更多