Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join and Include in Entity Framework

I have the following query of linq to entities. The problem is that it doesn't seem to load the "Tags" relation even though i have included a thing for it. It works fine if i do not join on tags but i need to do that.

            var items = from i in db.Items.Include("Tags")                         from t in i.Tags                         where t.Text == text                         orderby i.CreatedDate descending                         select i; 

Is there any other way to ask this query? Maybe split it up or something?

like image 470
Olaj Avatar asked Jan 06 '09 14:01

Olaj


People also ask

What is include in Entity Framework?

Entity Framework Classic Include The Include method lets you add related entities to the query result. In EF Classic, the Include method no longer returns an IQueryable but instead an IncludeDbQuery that allows you to chain multiple related objects to the query result by using the AlsoInclude and ThenInclude methods.

How do I join tables in Entity Framework?

Method Syntax Next, use the join extension method and specify the inner table as the first argument to the join method. . Join(db. EmailAddresses, The next two arguments specify the condition on which you want to join the tables.

How do I join a table in Entity Framework Core?

Entity Framework Core Joining In SQL, a JOIN clause is used to combine rows from two or more tables, based on a related column between them. In Entity Framework Core you can use the Join() and GroupJoin() method to achieve the same results. The following query joins Customers and Invoices table using the Join() method.

How do I join multiple tables in EF core?

The LINQ join operator allows us to join multiple tables on one or more columns (multiple columns). By default, they perform the inner join of the tables. We also learn how to perform left joins in EF Core by using the join operator & DefaultIfEmpty method. Also left join with where clause.


1 Answers

Well, the Include contradicts the where. Include says, "Load all tags." The where says, "Load some tags." When there is a contradiction between the query and Include, the query will always win.

To return all tags from any item with at least one tag == text:

        var items = from i in db.Items.Include("Tags")                     where i.Tags.Any(t => t.Text == text)                     orderby i.CreatedDate descending                     select i; 

(Untested, as I don't have your DB/model)

Here's a really good, free book on LINQ.

like image 89
Craig Stuntz Avatar answered Sep 19 '22 14:09

Craig Stuntz