views:

9362

answers:

2

I have the following query in linq to entities. The problem is that i doesn't seems to load the "Tags" relation even thou i have a include thingy 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?

+7  A: 

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.

Craig Stuntz
Any suggestions on how to write it in some other way so i can get the tags and do a condition on them. It would be kind of simple in regular SQL.
Stuck
Do you want to include ALL tags from ANY item with AT LEAST one tag == text?
Craig Stuntz
Yes! Thats what i want :)
Stuck
OK, try this (see answer).
Craig Stuntz
Thank you! I must buy a book or something on LINQ. That was really elegant.
Stuck
See updated answer for book. :)
Craig Stuntz
A: 

There is a problem with your answer:

Items are filtered correctly as written but Tags of each item are not filtered; I have the same problem with Object Query building.