0

i have the following LINQ statement:

var query =(from item in _itemRepository.FindAll()
            where item.Id == "20649458"
                from singelitem in item.ListOfChildren
                where singelitem.Property == "singelitem"
                from manyitems in item.ListOfChildren
                where manyitems.Property == "many"
                select new
                            {
                                item.Id,
                                singelitem,
                                manyitems 
                            });
var result = query.ToList();

Tasks is a collection of objects and the where clause tasks.Property == "something" matches several items in the collection, but when i use a anonymous type in the select, i only get back one item (the first) of the matching results instead of a collection of Tasks. How can i get back all the matching tasks in a collection?

Edit: What really happends is that i get flat objects, (just like a db result set from a join statement).

randoms
  • 2,713
  • 1
  • 29
  • 46

2 Answers2

3

When you don't use anonymous type you're dealing with entity class which lazy loads the tasks when you access them. If you want to load tasks with your results try using Include method to eager load children. See How do you construct a LINQ to Entities query to load child objects directly, instead of calling a Reference property or Load()

Community
  • 1
  • 1
Muhammad Hasan Khan
  • 33,106
  • 14
  • 80
  • 125
  • that does not really matter, since its the tasks that i want to be a list. i want one item (result) with a list of tasks.. – randoms Jun 04 '12 at 14:55
0

This is the proper behavior of Linq. In fact what you are expecting is not possible. You are expecting a single item matching item.Id == "123"; and what if more than one? it just creates an anonymous item for each matched item. Just think of changing the first "from" statement with the second one; what would you expect?

Also, there is no relationship between first "from" statement and the second one which makes this query a bit "strange". Why not just splitting the query into 2; and creating a new object with the desired properties?

daryal
  • 14,035
  • 4
  • 35
  • 54