3

I have imported my database into my EF Model,and I'm trying to create a linq query which returns the appropriate ViewModel.

The table Items reflects ItemDetailVM class

The table Property reflects PropertyVM class

There is a navigation property between Items and Property

The linq query im trying to write is below...

My question is how do I map the prop within ItemDetailVM?

var query = (from items in DbContext.Items
         select new ItemDetailVM
         {
            item1 = items.id,
            item2 = items.value,
            //prop = CODE HERE... select new PropertyVM{ ....}
         }).ToList();


class ItemDetailVM
{
    string item1;
    string item2;
    List<Property> prop;
}

class PropertyVM
{
    string prop1;
    string prop2;
    string prop3;
}
piris
  • 1,547
  • 3
  • 22
  • 26
  • Does each property have a reference to an item or do you want the full list of properties in each item? – jan Apr 07 '15 at 17:45
  • looks like you want to `eagerly load` the list ... http://stackoverflow.com/questions/3186009/linq-to-entities-eager-loading-using-include – Alex Apr 07 '15 at 17:46
  • I do not want the full list of properties, but a subset. The eager load would load all properties – piris Apr 07 '15 at 17:53
  • What condition do you want to apply to filter the properties? – ocuenca Apr 07 '15 at 17:56

1 Answers1

3

Try this:

var query = (from items in DbContext.Items
             select new ItemDetailVM
             {
               item1 = items.id,
               item2 = items.value,
               prop = items.prop.Select(p=>new PropertyVM{prop1=p.prop1,
                                                          prop2=p.prop2, 
                                                          prop3=p.prop3}).ToList()
             }).ToList();

If you have disabled lazy loading, then you need to call the Include extension method:

var query = (from items in DbContext.Items.Include(i=>i.prop)
             select new ItemDetailVM
             {
               item1 = items.id,
               item2 = items.value,
               prop = items.prop.Select(p=>new PropertyVM{prop1=p.prop1,
                                                          prop2=p.prop2, 
                                                          prop3=p.prop3}).ToList()
             }).ToList();
ocuenca
  • 38,548
  • 11
  • 89
  • 102