LINQ to SQL:多个列上的多个连接.这可能吗?

LINQ to SQL: Multiple joins ON multiple Columns. Is this possible?(LINQ to SQL:多个列上的多个连接.这可能吗?)
本文介绍了LINQ to SQL:多个列上的多个连接.这可能吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

Given:

A table named TABLE_1 with the following columns:

  • ID
  • ColumnA
  • ColumnB
  • ColumnC

I have SQL query where TABLE_1 joins on itself twice based off of ColumnA, ColumnB, ColumnC. The query might look something like this:

Select t1.ID, t2.ID, t3.ID
  From TABLE_1 t1
  Left Join TABLE_1 t2 On
       t1.ColumnA = t2.ColumnA
   And t1.ColumnB = t2.ColumnB
   And t1.ColumnC = t2.ColumnC
  Left Join TABLE_1 t3 On
       t2.ColumnA = t3.ColumnA
   And t2.ColumnB = t3.ColumnB
   And t2.ColumnC = t3.ColumnC
... and query continues on etc.

Problem:

I need that Query to be rewritten in LINQ. I've tried taking a stab at it:

var query =
    from t1 in myTABLE1List // List<TABLE_1>
    join t2 in myTABLE1List
      on t1.ColumnA equals t2.ColumnA
      && t1.ColumnB equals t2.ColumnA
    // ... and at this point intellisense is making it very obvious
    // I am doing something wrong :(

How do I write my query in LINQ? What am I doing wrong?

解决方案

Joining on multiple columns in Linq to SQL is a little different.

var query =
    from t1 in myTABLE1List // List<TABLE_1>
    join t2 in myTABLE1List
      on new { t1.ColumnA, t1.ColumnB } equals new { t2.ColumnA, t2.ColumnB }
    ...

You have to take advantage of anonymous types and compose a type for the multiple columns you wish to compare against.

This seems confusing at first but once you get acquainted with the way the SQL is composed from the expressions it will make a lot more sense, under the covers this will generate the type of join you are looking for.

EDIT Adding example for second join based on comment.

var query =
    from t1 in myTABLE1List // List<TABLE_1>
    join t2 in myTABLE1List
      on new { A = t1.ColumnA, B = t1.ColumnB } equals new { A = t2.ColumnA, B = t2.ColumnB }
    join t3 in myTABLE1List
      on new { A = t2.ColumnA, B =  t2.ColumnB } equals new { A = t3.ColumnA, B = t3.ColumnB }
    ...

这篇关于LINQ to SQL:多个列上的多个连接.这可能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

LINQ to SQL query using quot;NOT INquot;(使用“NOT IN的 LINQ to SQL 查询)
How to do a full outer join in Linq?(如何在 Linq 中进行完整的外部联接?)
LINQ to SQL Web Application Best Practices(LINQ to SQL Web 应用程序最佳实践)
How do I group data in an ASP.NET MVC View?(如何在 ASP.NET MVC 视图中对数据进行分组?)
how to update the multiple rows at a time using linq to sql?(如何使用 linq to sql 一次更新多行?)
how to recognize similar words with difference in spelling(如何识别拼写不同的相似词)