[英]Trying to understand my IEnumerable and why I can't use .ToList()
我目前对我的一种数据对象回购模式有以下方法:
public async Task<IEnumerable<DropDownList>> GetDropDownListNoTracking()
{
return await context.TouchTypes
.AsNoTracking()
.Where(s => s.IsActive)
.Select(s => new DropDownList()
{
Id = s.Id,
Name = s.Description
}).ToListAsync();
}
当我在页面视图中调用它时:
private IList<DropDownList> TouchTypeList { get; set; }
private async Task LoadDropDownAsync()
{
TouchTypeList = await _unitOfWork.TouchType.GetDropDownListNoTracking();
}
我试图理解为什么我不能只做GetDropDownListNoTracking().ToList()
而是要我投射: (IList<DropDownList>)
。
我可以轻松地更改属性来解决这个问题,但我认为.ToList
可以在这里工作吗?
我主要是想理解这一点,以便我能以正确的方式做到这一点。
GetDropDownListNoTracking
返回Task<IEnumerable<DropDownList>>
,而不是IEnumerable<DropDownList>
,所以你必须这样做:
private async Task LoadDropDownAsync()
{
TouchTypeList = (await _unitOfWork.TouchType.GetDropDownListNoTracking()).ToList();
}
对一个您知道实际上总是列表的可枚举调用ToList
会浪费 CPU 周期,并且表明您的方法的返回类型选择不当。 最简单的解决方案是将您的方法更改为:
public async Task<IList<DropDownList>> GetDropDownListNoTracking()
{
return await context.TouchTypes
.AsNoTracking()
.Where(s => s.IsActive)
.Select(s => new DropDownList()
{
Id = s.Id,
Name = s.Description
}).ToListAsync();
}
虽然我个人会改用IReadOnlyList
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.