Frage

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.

War es hilfreich?

Lösung

Your properties variable is null, hence you get a NullReferenceException - just initialize it with an instance of a concrete class that implements IList<PropertyViewModel>:

IList<PropertyViewModel> properties = new List<PropertyViewModel>();

A better solution would be to get all the related PropertyImages in one query by using an EF Include() 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 related PropertyImages for each property:

var properties = db.Properties
                   .Include( x=> x.PropertyImages);
                   .Select( x => new PropertyViewModel(x, x.PropertyImages.ToList())
                   .ToList();
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top