Nitin Agrawal
Nitin Agrawal

Reputation: 29

Entity Framework Join vs Include

I am using EF6.1 and bit confused with the two formats of writing the join queries.

var query = (from cc in dbContext.Companies.AsNoTracking()
             join dc in dbContext.Departments.AsNoTracking() 
             on cc.CompanyId equals dc.CompanyId
                select new {cc,dc}).ToList().Select(k=> New Company()
                              {
                                 CompanyId = k.cc.CompanyId,
                                 Departments = k.dc.ToList()
                              });

vs

var query = dbContext.Comapanies.Include(k=>k.Departments).ToList();

My question is which one should be use and what are the pros and cons.

I found mix feedback on using the Include in case of multiple tables.

As per below article https://msdn.microsoft.com/en-in/data/jj574232.aspx

"Note that it is not currently possible to filter which related entities are loaded. Include will always being in all related entities."

this statement is not very clear as well. Please suggest.

Upvotes: 3

Views: 5097

Answers (2)

mBardos
mBardos

Reputation: 3067

You'll have to use the first version if you want to connect your entities on more than a single ID field. Or use the EF Core 5's Filter Include expression (see this SO topic).

Upvotes: 0

M.Aamir Niazi
M.Aamir Niazi

Reputation: 19

"Note that it is not currently possible to filter which related entities are loaded. Include will always being in all related entities."

**This statement means, if tables have proper relation defined in database then 'Inclues' will work, but join statement does not need any relationship defined in database

its the key point while making decession to use inclue or join, btw includes are more proper as that are already managed in DB and in entity too

Upvotes: 2

Related Questions