简体   繁体   中英

LINQ table join with entity Framework

In my database I have ... TableA, TableB and TableC

TableB has just 2 columns, the primary key of TableA and TableC, so it really defines a one to many relationship between the two tables

What I want to do using SQL is:

SELECT * 
FROM TablesA a
JOIN TablesB b ON a.AID = b.AID
WHERE b.BID = 1

In the Entity Framework it doesn't create a TablesB for me to do the join, I think because TableB only has foreign keys!

So how can I do it?

Doing a join with LINQ is fairly straightforward

from a in TablesA
join b in TablesB
on a.AID equals b.AID
into joined
where b.BID == 1
select joined

I think the real question may be - why don't you have an entity class for TablesB ? We may need more information to answer that.

When you import the tables from database, entity framework gets rid of the TableB table and shows TableA and TableC to have many to many relationships. TableA has a navigation property TableCs and vice versa. So all you need to use these navigation properties, for sample:

var tableARow= db.TableA.First(s => s.Id == 1); 
if (!tableARow.TableCs.IsLoaded) { tableARow.TableCs.Load(); }

or

var tableARow= db.TableA.Include("TableCs").First(s => s.Id == 1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM