Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq Join() with composite key

Tags:

c#

linq

I'm trying to make a request with two tables

Table Page : Id, LangId (primary key) PageTypeId, PageTypeLangId (foreign key)

Table PageType : Id, LangId (primary key)

So How to do ? Here, i miss just do add PageTypeLangId

    return context.Pages
            .Join(context.PageTypes, p => p.PageTypeId, pT => pT.Id,(p, pT) => new { p, pT })

i would like :

 select * from Page inner join PageType on Page.PageTypeId=PageType.Id and     Page.PageTypeLangId=PageType.LangId

Thanks for your help !

like image 408
Olivier Albertini Avatar asked Feb 22 '13 21:02

Olivier Albertini


People also ask

What type of key is being in this Linq to join the data from three tables?

This is accomplished by using a composite key.

Can we use joins in Linq?

In LINQ, an inner join is used to serve a result which contains only those elements from the first data source that appears only one time in the second data source. And if an element of the first data source does not have matching elements, then it will not appear in the result data set.

Is Linq join inner or outer?

When you use the LINQ join clause in the query expression syntax to combine two sets of related information, you perform an inner join.


1 Answers

The following should work:

return context.Pages
              .Where(x => x.PageTypeLangId.HasValue)
              .Join(context.PageTypes,
                    p => new { Id = p.PageTypeId,
                               LangId = p.PageTypeLangId.Value },
                    pT => new { pT.Id, pT.LangId },
                    (p, pT) => new { p, pT });
like image 157
Daniel Hilgarth Avatar answered Sep 23 '22 04:09

Daniel Hilgarth