【问题标题】:Entity Framework - A 'GetAll' function using a View Model实体框架 - 使用视图模型的“GetAll”函数
【发布时间】:2011-09-21 21:49:20
【问题描述】:

我创建了以下视图模型:

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 变量。任何建议将不胜感激。

【问题讨论】:

    标签: c# asp.net-mvc entity-framework asp.net-mvc-viewmodel


    【解决方案1】:

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

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

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

    编辑:

    这应该等同于使用 EF Include() 查询,它将获取每个属性的相关 PropertyImages

    var properties = db.Properties
                       .Include( x=> x.PropertyImages);
                       .Select( x => new PropertyViewModel(x, x.PropertyImages.ToList())
                       .ToList();
    

    【讨论】:

    • 非常感谢您这么迅速的回答!我是新手,如何使用Include() 进行更有效的查询?
    猜你喜欢
    • 1970-01-01
    • 2012-07-03
    • 1970-01-01
    • 1970-01-01
    • 2016-02-19
    • 1970-01-01
    • 2011-04-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多