我应该何时在viewModel中使用ICollection <t>或IEnumerable <t>?

时间:2017-03-09 16:05:48

标签: c# asp.net-mvc

使用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?

0 个答案:

没有答案