Reputation: 97
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.
Upvotes: 3
Views: 3656
Reputation: 39326
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 TableB
to 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]}
Upvotes: 3
Reputation: 3662
var table = from a in db.tbA
join ab in db.tbAB on a.idA equals ab.idA
join b in db.tbB on ab.idB equals b.idB
where a.Anything = 10
select a;
var results = table.ToList();
Upvotes: 0
Reputation: 13888
public void Test()
{
var db = new DbContext();
// This will automatically do you inner join for you.
db.TableAs.Include(a => a.TableBs);
}
Context:
public class DbContext
{
public IDbSet<TableA> TableAs { get; set; }
public IDbSet<TableB> TableBs { get; set; }
}
Models:
public class TableA
{
public int Id { get; set; }
public virtual List<TableB> TableBs { get; set; }
}
public class TableB
{
public int Id { get; set; }
public virtual List<TableA> TableAs { get; set; }
}
Upvotes: 1