如何在 linq 查询中设置内连接

Posted

技术标签:

【中文标题】如何在 linq 查询中设置内连接【英文标题】:How to set inner join in linq query 【发布时间】:2021-08-03 09:56:29 【问题描述】:

我想在 linq 查询中设置内连接

这是我的代码,

var JoinUsingMS = from emp in _productRepository.Table
   join address in _purchaseReminderRepository.Table
  on new  c1 = emp.VendorId, c2 = emp.Name  equals new  c1 = address.VendorId, c2 = address.Product  into bp_sm
   from c in bp_sm.DefaultIfEmpty()
   where emp.Published == true
   select emp;

从这个查询中,我得到了左连接(通过调试跟踪)。虽然我认为这个查询非常适合内连接(参考链接As Per This Solution)仍然输出得到左连接

【问题讨论】:

【参考方案1】:

下面更新了内部连接的查询:

var JoinUsingMS = from emp in _productRepository.Table
   join address in _purchaseReminderRepository.Table
   on new  c1 = emp.VendorId, c2 = emp.Name  
   equals new  c1 = address.VendorId, c2 = address.Product 
   where emp.Published == true
   select emp;

【讨论】:

【参考方案2】:

简单。删除DefaultIfEmpty 行。这就是创建左连接子句的原因:

var JoinUsingMS = 
    from emp in _productRepository.Table
    join address in _purchaseReminderRepository.Table
      on new  c1 = emp.VendorId, c2 = emp.Name  equals new  c1 = address.VendorId, c2 = address.Product  // into bp_sm
    // from c in bp_sm.DefaultIfEmpty()
    where emp.Published == true
    select emp;

【讨论】:

以上是关于如何在 linq 查询中设置内连接的主要内容,如果未能解决你的问题,请参考以下文章