Question

I am trying to get from 3 related tables by using LINQ. But when I use 2 joins, the result takes only elements getting from 2nd join. Here is my code:

var myAssList = mldb.Assigns
                .Join(mldb.Lists,
                      a => a.list_id,
                      l => l.id,
                      (a, l) => new {
                         Assign = a,
                         List = l 
                     })                
                .Where(a => a.Assign.assigned_to == "myname")
                .Join(mldb.Elements,
                      li => li.List.id,
                      e => e.parent_server_id,
                      (li, e) => new { 
                         Element = e 
                      });

var jsonSerialiser = new JavaScriptSerializer();
var listListJson = jsonSerialiser.Serialize(myAssList);

this Json return only attributes from Element(e) and List(li). But I want to get also the attributes from Assign(a).

The SQL query I am trying to realize in LINQ is that:

select * from Assigns 

inner join Lists 
on Assigns.server_list_id=Lists.id

inner join Elements
on Lists.id=Elements.parent_id

where Assigns.assigned_to='myname'

So, how can I get the attributes from the first join also (from "a", "l" and "e")?

Was it helpful?

Solution

You can access Assign entity from outer sequence li variable:

.Join(mldb.Elements,
      li => li.List.id,
      e => e.parent_server_id,
      (li, e) => new { 
         Element = e,
         Assign = li.Assign // here
      });

OTHER TIPS

from a in mldb.Assigns
join l in mldb.Lists on a.list_id equals l.id
join e in mldb.Elements on l.id equals e.parent_server_id
where a => a.Assign.assigned_to == "myname"
select new { Assign = a, Element = e }

This is so called "query syntax". It makes LINQ expressions looks like SQL queries. In the end they are translated to IEnumerable extension methods. If you want to join multiple tables then query syntax is more readable. Another useful feature of query syntax is let clause. With the aid of it, you can declare additional variables inside your queries.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top