2

I am selecting an Anonymous Object in Entity Framework. I am including Sub-Properties into the Anonymous Object.

This is very similar to the question here. The difference is, I am including multiple (two) levels deep.

For example:

context.Items.Include(x => x.ChildItems.Select(y => y.House)).ToList();
//                                     ^^^^^^^^^^^^^^^^^^^^^

With the basic selection above, ChildItems and their associated House are all populated. But if I try to select an anonymous object like below, the ChildItems exist, but their House item is null.

context.Items.Include(x => x.ChildItems.Select(y => y.House))
    .Select(x => new
    {
        x.ItemID,
        x.OtherInfo,
        x.ChildItems,
    }).ToList();
Erik Philips
  • 53,428
  • 11
  • 128
  • 150
Suamere
  • 5,691
  • 2
  • 44
  • 58
  • Why do you want to do this? The whole point of most ORMs is to materialize run-time classes that represent rows in a database. – Erik Philips Mar 28 '18 at 21:59
  • @ErikPhilips This is the standard method for selecting specific columns (or, IOW, omitting specific columns) when selecting data. If a table has an inordinate number of columns, or certain columns with an inordinate amount of data, which is unnecessary to pull back from the database, you perform an anonymous selection on the queryable, then re-materialize it into the Entity. – Suamere Mar 28 '18 at 22:36
  • Then don't use Entity FrameWork or any ORM for that matter when doing that. [You can use EF to make your own calls via `DbContext.Database.SqlQuery()`](https://stackoverflow.com/questions/4873607/how-to-use-dbcontext-database-sqlquerytelementsql-params-with-stored-proced) and materialize the objects with the properties you don't need. Otherwise don't use EF if you aren't going to map them to real objects. – Erik Philips Mar 28 '18 at 23:16

0 Answers0