繁体   English   中英

如何通过多个字段(2个表1 PK至2 FK)加入LINQ C#Linq

[英]How to join in LINQ by multiple fields (2 TABLES 1 PK to 2 FK ) c# linq

我有2张桌子:

  • 顾客
  • 关联客户

已连接的客户表包含两个到客户表的外键,基本上看起来像这样:

在此处输入图片说明

我想知道的是如何从相关表中退回两个客户?

我已经尝试过这样的事情(不允许):

query = from c in _context.Customers join cc in _context.ConnectedCustomers
         on c.customerId equals cc.customer1_id OR c.Id equals cc.customer2.id
        select c;

而且这是不允许的...因此,我在Google上进行了一些搜索,发现在这种情况下,人们通常使用匿名类型,因此我尝试了以下方法:

这也不起作用,因为我包括了两次 c.customerId,并且它说anonymous type cannot have multiple properties with the same name

query =  from c in _context.Customers join cc in _context.ConnectedCustomers
           on new { c.customerId, c.customerId } equals new { cc.customer1_id, cc.customer2 }
        select c;

所以我从匿名类型中删除了c.customerId之一,它看起来像这样:

query =  from c in _context.Customers join cc in _context.ConnectedCustomers
           on new { c.customerId } equals new { cc.customer1_id, cc.customer2 }
        select c;

但是比我收到的关于连接的错误说: The type of one of the expressions in the join clausule is incorrect...

多谢你们 !

干杯

抱歉,不能完全清楚期望的结果是什么,但是我相信您只需要ConnectedCustomers中存在的“客户”表中的“客户”? 如果没有评论让我知道,我可以进行更新,但是使用流畅的语法看起来像这样:

var myCustomers = _context.Customers.Select(c => _context.ConnectedCustomers.Any(cc => cc.customer1_id.Equals(c.customerId) || cc.customer2_id.Equals(c.customerId)).ToList();

您可以将其加入2个单独的查询中,并对其进行合并/合并,也可以使用where条件(交叉连接+ where条件,当心重复项)以“旧的fashiend方式”将其加入:

var query = from cust in _context.Customers 
            join custcon in _context.ConnectedCustomers
            where cust.customer_id == custcon.customer1_id
              or cust.customer_id == custcon.customer2_id
            select cust;

如果要“从关系表中退回两个客户”,则可以简单地两次加入该客户并返回包含两个客户的匿名对象(或您选择的新类):

var query = from custcon in _context.ConnectedCustomers
            join cust1 in _context.Customers on custcon.customer1_id equals cust1.customer_id
            join cust2 in _context.Customers on custcon.customer2_id equals cust1.customer_id
            select new { Customer1 = cust1, Customer2 = cust2};

来自: 执行自定义联接操作

但是,在以下情况下不能使用join子句:

  • 当联接基于不等式(非等联接)表示时。
  • 当连接基于多个相等或不相等的表达式时。
  • 在必须在联接操作之前为右侧(内部)序列引入临时范围变量时。

根据第二点,您的案子似乎符合非等额资格。


因此,您可以使用where子句进行交叉连接(此处的条件是一个表达式,因此它可以随您的意愿而复杂):

var query  = from c in _context.Customers
        from cc in _context.ConnectedCustomers
        where c.customerId == cc.customer1_id || c.customerId == cc.customer2_id
        select c.customerId;

或者只是简单地做两个等联接并将它们组合:

var q1 = from c in _context.Customers
         join cc in _context.ConnectedCustomers
         on c.customerId equals cc.customer1_id
         select c.customerId;

var q2 = from c in _context.Customers
         join cc in _context.ConnectedCustomers
         on c.customerId equals cc.customer2_id
         select c.customerId;

var query = q1.Concat(q2);

编辑:固定变量名称并删除Distinct()子句,因为未指定是否需要它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM