Reputation: 1595
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;
}
Upvotes: 3
Views: 881
Reputation: 39376
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();
Upvotes: 3