简体   繁体   中英

How to join one row to every row in source table using LINQ

I have the following table (table A):

ID | Data  |
1  | Data1 |
2  | Data2 |
3  | Data3 |
4  | Data4 |

I have table B that has 1 row :

DummyID | Dummy  |
1       | Dummy1 |

I have to join table A with table B in the following way:

ID | Data  |DummyID | Dummy  |
1  | Data1 |1       | Dummy1 |
2  | Data2 |1       | Dummy1 |
3  | Data3 |1       | Dummy1 |
4  | Data4 |1       | Dummy1 |

Obviously I can't use any ID in the on clause.

from item in context.TableA
join dummy in context.TableB on ? = ?
select new 
 {
  RowA=item,
  Dummy=dummy
 }

How could I do that with LINQ?

That's a cross join which you can get via Linq in the following way

from item in context.TableA
from dummy in context.TableB
select new 
 {
  RowA=item,
  Dummy=dummy
 }

Or the following in method syntax

context.TableA.SelectMany(
    item => context.TableB.Select(dummy => new { RowA = item, Dummy = dummy }));

Note that if TableB every has more than one row you'll end up with N times M rows where N is the number of rows in TableA and M is the number of rows in TableB.

No need to join at all.

from item in context.TableA
select new 
{
    RowA = item,
    Dummy = context.TableB.FirstOrDefault()
}

Having said that, I'd have to question why you're doing this. The idea of LINQ is to get your relational data into an object-oriented form. Why not just retrieve the TableB information once and do whatever processing you need to do in-memory? It would reduce the size of the payload you're transferring from the database back to the application.

Why do you want to use join. You want to use each item in your old sequence to create a different item in your new sequence. In LINQ you would use Enumerable.Select for this:

var dummy = context.Dummy.FirstOrDefault();
var newSequence = context.TableA
    .Select(itemInTableA =>
        new
        {
            RowA = itemInTableA,
            Dummy = dummy,
        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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