使用IEnumerable
查看模型
public class ResumeDetailsViewModel
{
public IEnumerable<WorkExperience> WorkExperiences { get; set; }
}
控制器中的
var workExperiences = _dbContext.WorkExperiences.Where(w => w.UserId == userId);
var viewModel = new ResumeDetailsViewModel
{
WorkExperiences = workExperiences,
};
在视图中
@if (Model.WorkExperiences.Any())
{
foreach (var workExperience in Model.WorkExperiences)
{
@workExperience.JobTitle
}
}
使用ICollection
查看模型
public class ResumeDetailsViewModel
{
public ICollection<WorkExperience> WorkExperiences { get;set; }
}
控制器中的
var workExperiences = _dbContext.WorkExperiences.Where(w => w.UserId == userId);
var viewModel = new ResumeDetailsViewModel
{
WorkExperiences = workExperiences.ToList()
};
在视图中
@if (Model.WorkExperiences.Any())
{
foreach (var workExperience in Model.WorkExperiences)
{
@workExperience.JobTitle
}
}
我希望尽可能少查询。在我的示例中,两种方法都为IEnumerable创建了2个查询Model.WorkExperiences.Any()
和var workExperience in Model.WorkExperience
,而对于ICollection创建了workExperiences.ToList()
和Model.WorkExperiences.Any()
。
如果我的假设错了,请纠正我。
我应该何时使用ICollection或IEnumerable?