Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to join 3 tables with linq

I am trying to join 3 tables in a query with Linq to get data from all 3 tables. Below is an image of the table schemes:

enter image description here

The query should select: SewagePlantName, CompanyName and Duty

In addition I need to restricts the SewagePlantId to a list of Ids that are given as:

            var sewagePlantIds = UnitOfWork.GetAll<UserGroup>()
            .Where(group => group.Id == webAppPrincipal.GroupId)
            .SelectMany(group => group.SewagePlantId).Select(sewageplant => sewageplant.Id).ToList();

I have difficulties with the order of joining the 3 tables and where/how to restrict the SewagePlantId to the given list.

like image 911
Manu Avatar asked Jan 30 '17 10:01

Manu


People also ask

Can you join 3 tables together?

It is possible to use multiple join statements together to join more than one table at the same time. To do that you add a second INNER JOIN statement and a second ON statement to indicate the third table and the second relationship.

How do I join two LINQ queries?

LINQ Join queries. As we know the JOIN clause is very useful when merging more than two table or object data into a single unit. It combines different source elements into one and also creates the relationship between them. Using the join, you can grab the data based on your conditions.

Can we do joins in LINQ?

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. In LINQ, explicit join clauses are only required when two source sequences are not tied by any relationship.


2 Answers

var obj = from trns in context.tblPartyRegistrations
          join st in context.tblSellingTrans
          on trns.PartyRegId equals st.Fk_PartyRegId
          join pt in context.tblPartyRemainings
          on trns.PartyRegId equals pt.fk_PartyId
          select new
          {
              trns.Name,
              trns.PhoneNo,
              trns.Address,
              st.RecivedAmount,
              st.Date,
              st.CustomerType,
              st.MilkRate,
              st.Mltr,
              st.Mkg,
              st.NtAmnt,
              st.RemaningAmount,
              pt.Remainingammount
          };
like image 189
user8191706 Avatar answered Nov 03 '22 02:11

user8191706


Can you try something similar to it please for joining part

from d in Duty
join c in Company on d.CompanyId equals c.id
join s in SewagePlant on c.SewagePlantId equals s.id
select new
  {
      duty = s.Duty.Duty, 
      CatId = s.Company.CompanyName,
      SewagePlantName=s.SewagePlant.SewagePlantName
      // other assignments
  };
like image 44
Bits_Please Avatar answered Nov 03 '22 02:11

Bits_Please