Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq query with many to many relations using entity framework

I have two tables: tbA and tbB .Between them I have a relationship n to n, so a table tbAB was generated in the database. I am using an Entity Framework Database First, then when I mapped these tables , it does not generate a specific entity for tbAB. Thus , I'm not seeing how I can create a query relating the two tables if I can't call directly thetbAB. What I want to do in SQL would be as follows :

 SELECT * 
 FROM tbA
 INNER JOIN tbAB 
 ON tbAB.idA = tbA.idA
 INNER JOIN tbB
 ON tbB.idB = tbAB.idB

That's what I'm trying to do with Linq:

  var table = (from l in db.tbA
                                            join k in db.tbB on l.? equals k.?
                                            where ?.IDCONCESSAO == objectTbB.IDCONCESSAO
                                            select l).ToList();

The question is how can I do this in a Linq expression ?

Thanks in advance.

like image 997
Jessica Avatar asked Feb 19 '26 02:02

Jessica


1 Answers

Following the model proposed by @Michal, you could do this:

var query= from a in db.TableAs
           from b in a.TableBs
           where b.Id==10
           select new{A_Id=a.Id,a.Name, B_Id=b.Id,b.Price,...};

In the select you can choose the properties you need from both entities(I also select a Name from TableA and a Price from TableBto help you understand better this example).From each direction of the relationship, you don’t ever interact with the junction table, you just follow a relationship from each direction as if it were a one-to-many. The query that I show above will be translated in a sql query where the joins between the tables will be made this way:

{SELECT 
[Extent1].[Id] AS [Id], 
[Extent1].[Name] AS [Name], 
[Join1].[Id] AS [Id1], 
[Join1].[Price] AS [Price]
FROM  [dbo].[TableAs] AS [Extent1]
INNER JOIN  (SELECT [Extent2].[TableA_Id] AS [TableA_Id], [Extent3].[Id] AS [Id], [Extent3].[Price] AS [Price]
    FROM  [dbo].[TableBTableAs] AS [Extent2]
    INNER JOIN [dbo].[TableBs] AS [Extent3] ON [Extent3].[Id] = [Extent2].[TableB_Id] ) AS [Join1] ON [Extent1].[Id] = [Join1].[TableA_Id]
WHERE 10 = [Join1].[Id]}
like image 89
octavioccl Avatar answered Feb 20 '26 16:02

octavioccl