Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ joining two tables

I have two tables say A and B. A cols are GUID, someintVar, someMoreIntvar B col are GUID, someItemNO, SomeItemDesc

Now for one GUID I will have only one row in Table A. But I can have multiple rows for the same GUID. Now I want to query the database based on GUID and select values in a class. This class will have a list that will hold different rows coming from the second table. How can I do it?

Right Now I am getting many items in the result based on how many rows are there in the second table for that GUID.

var itemColl = from p in db.A
               join item in db.B on p.CardID equals item.CardID
               where p.CardID == "some GUID"
               select new 
               {
                   p.CardID,
                   p.secondCol,
                   p.ThirdCol,
                   item.ItemNo // How to add them in a collection or list.
               };
like image 776
Tanmoy Avatar asked Mar 04 '09 15:03

Tanmoy


People also ask

Can we use joins in Linq?

relational tables. In a LINQ query expression, join operations are performed on object collections. Object collections cannot be "joined" in exactly the same way as two relational tables.

What is group join in Linq?

The group join is useful for producing hierarchical data structures. It pairs each element from the first collection with a set of correlated elements from the second collection. For example, a class or a relational database table named Student might contain two fields: Id and Name .

How do I combine two tables in net core?

Provide the Project name such as "JoinDataTableUsingLINQ" or another as you wish and specify the location. Then right-click on Solution Explorer and select "Add New Item" then select Default. aspx page. Drag and drop three Grid view to bind the records after Joining the two data table .


1 Answers

Unested, but how about re-writing it a bit:

var itemColl = from p in db.A
               where p.CardID == "some GUID"
               select new {
                   p.CardID,
                   p.secondCol,
                   p.ThirdCol,
                   Items = db.B.Where(b=>b.CardID==p.CardID)
                      //.Select(b=>b.ItemNo) [see comments]
               }

Alternatively, you could perhaps group...

like image 101
Marc Gravell Avatar answered Sep 17 '22 13:09

Marc Gravell