I’ve created the following view model:
public class PropertyViewModel
{
public PropertyViewModel(Property property, IList<PropertyImage> images)
{
this.property = property;
this.images = images;
}
public Property property { get; private set; }
public IList<PropertyImage> images { get; private set; }
}
Now i need to create a function that gets all the properties in the database along with their associated images. Is it possible to do this using the viewmodel above? I have tried the following.
public IList<PropertyViewModel> GetAllPropertyViews()
{
IList<PropertyViewModel> properties = null;
foreach (var property in GetAllProperties().ToList())
{
IList<PropertyImage> images = db.PropertyImages.Where(m => m.Property.PropertyID == property.PropertyID).ToList();
properties.Add(new PropertyViewModel(property, images));
}
return properties;
}
This doesn’t work, it gives “Object reference not set to an instance of an object.” at properties.Add(new PropertyViewModel(property, images));
For the paginatation method i’m using i need to return an IQueryable variable. Any suggestions would be greatly appreciated.
Your properties variable is
null, hence you get aNullReferenceException– just initialize it with an instance of a concrete class that implementsIList<PropertyViewModel>:A better solution would be to get all the related
PropertyImagesin one query by using an EFInclude()query – your repository layer (that you seem to have on top of EF) must support this though. Currently you are executing N queries on your database, one for each property.Edit:
This should be the equivalent using EF
Include()query, which will grab the relatedPropertyImagesfor each property: