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

时间:2019-07-31 08:06:19

标签: c# linq

我有2张桌子:

  • 客户
  • ConnectedCustomers

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

enter image description here

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

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

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...

谢谢大家!

欢呼

3 个答案:

答案 0 :(得分:0)

很抱歉,

尚不清楚您想要的结果是什么,但是我相信您只希望ConnectedCustomers中存在的客户表中的客户?如果没有评论让我知道并且可以进行更新,但是使用流畅的语法看起来像这样:

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

答案 1 :(得分:0)

您可以在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;

如果要“从关系表中退回两个客户”,只需将客户加入2次,然后返回包含两个客户的匿名对象(或您选择的新类):

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};

答案 2 :(得分:0)

发件人:Perform custom join operations

  

但是,在以下情况下,不能使用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);

EDIT:修复了变量名,并删除了Distinct()子句,因为未指定是否需要它。

相关问题