I currently have the following method for one of my data objects repo patterns:
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();
}
When I call it in my page view :
private IList<DropDownList> TouchTypeList { get; set; }
private async Task LoadDropDownAsync()
{
TouchTypeList = await _unitOfWork.TouchType.GetDropDownListNoTracking();
}
I'm trying to understand why I can't just do a GetDropDownListNoTracking().ToList()
but instead, it wants me to cast : (IList<DropDownList>)
.
I can easily just change the property to fix this but I would assume .ToList
would work here?
I'm mostly just trying to understand this so I can do it the correct way.
CodePudding user response:
GetDropDownListNoTracking
returns Task<IEnumerable<DropDownList>>
, not IEnumerable<DropDownList>
, so you'd have to do:
private async Task LoadDropDownAsync()
{
TouchTypeList = (await _unitOfWork.TouchType.GetDropDownListNoTracking()).ToList();
}
CodePudding user response:
Calling ToList
on an enumerable that you know is really always a list is a waste of CPU cycles, and points to a poor choice of return type for your method. The simplest solution is to change your method to:
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();
}
Although I personally would use IReadOnlyList
instead.