1

我创建了以下视图模型:

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; }
}

现在我需要创建一个函数来获取数据库中的所有属性及其相关图像。是否可以使用上面的视图模型来做到这一点?我尝试了以下方法。

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;
    }

这不起作用,它给出“对象引用未设置为对象的实例”。在properties.Add(new PropertyViewModel(property, images));

对于我正在使用的分页方法,我需要返回一个 IQueryable 变量。任何建议将不胜感激。

4

1 回答 1

3

您的属性变量是null,因此您得到一个NullReferenceException- 只需使用实现的具体类的实例对其进行初始化IList<PropertyViewModel>

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

PropertyImages更好的解决方案是通过使用 EF 查询在一个查询中获取所有相关Include()信息 - 您的存储库层(您似乎在 EF 之上)必须支持这一点。目前,您正在数据库上执行 N 个查询,每个属性一个。

编辑:

这应该与使用 EFInclude()查询等效,它将获取PropertyImages每个属性的相关信息:

var properties = db.Properties
                   .Include( x=> x.PropertyImages);
                   .Select( x => new PropertyViewModel(x, x.PropertyImages.ToList())
                   .ToList();
于 2011-09-21T21:52:14.643 回答