实体框架 - 使用视图模型
问题描述:
A“GETALL”功能
我创建了以下视图模型:实体框架 - 使用视图模型
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; }
}
现在我需要创建一个获取数据库中的所有属性及其关联沿功能图片。是否有可能使用上面的viewmodel来做到这一点?我已经尝试了以下。
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));
对于paginatation方法我使用我需要返回一个IQueryable变量。任何建议将不胜感激。
答
你的属性变量是null
,因此你会得到一个NullReferenceException
- 只是实现IList<PropertyViewModel>
一个具体的类的实例初始化:
IList<PropertyViewModel> properties = new List<PropertyViewModel>();
一个更好的解决办法是让所有在一个相关PropertyImages
查询 - 使用EF Include()
查询 - 您的存储库层(您似乎在EF之上)必须支持这一点。目前,您正在数据库上执行N个查询,每个属性一个查询。
编辑:
这应该是等同采用EF Include()
查询,它会抓住每个属性的相关PropertyImages
:
var properties = db.Properties
.Include(x=> x.PropertyImages);
.Select(x => new PropertyViewModel(x, x.PropertyImages.ToList())
.ToList();
非常感谢这样一个快速的答案!我对此很陌生,我如何使用'Include()'来获得更高效的查询? –
@Michael:更新的答案显示等效 – BrokenGlass