简体   繁体   中英

Async, await and Task with ToList

I am attempting to learn how to use await and async.

I have a service layer, which has a reference data manager. My interface is:

public interface IReferenceDataService
    {
        Task<List<ReferenceItemDto>> GetAsync(ReferenceTypes type);
    }

When I try get my data in the UI, I am doing this:

    model.DeptPaymentTypes = _refDataService.GetAsync(Enums.ReferenceTypes.DeptPaymentTypes)
       .Select(x => new SelectListItem { 
          Text = x.Description, 
          Value = x.Id.ToString() })
        .ToList();

But am getting an error that, "ToList is not a definition for Task<..."

My data layer calls gets the data using Dapper QueryAsync...

 public async Task<List<ReferenceItemDto>> GetAsync(Enums.ReferenceTypes type)
        {
            var table = string.Empty;

            if(type == Enums.ReferenceTypes.DaysOfMonth)
            {
                var days = new List<ReferenceItemDto>();
                for (int i = 1; i <= 31; i++)
                {
                    days.Add(new ReferenceItemDto
                    {
                        Description = i.ToString(),
                        Id = i
                    });
                }
                return days;
            }


            switch (type)
            {
                case Enums.ReferenceTypes.SnowballTypes:
                    table = "SnowballType";
                    break;
                case Enums.ReferenceTypes.DeptPaymentTypes:
                    table = "DebtPaymentType";
                    break;
                default:
                    throw new System.Exception("Unknown data type in referenc manager.");

            }
            using (IDbConnection db = new SqlConnection("Data Source=......"))
            {
                var data = await db.QueryAsync<ReferenceItemDto>("GetReferenceDataList", new { DataType = table }, commandType: CommandType.StoredProcedure);
                return data.ToList();
            }

        }

What am I doing wrong? The ToList is causing me an issue.

You should get a result from your async method. It's better to avoid blocking calls like Result , so use await instead.

model.DeptPaymentTypes = (await _refDataService.GetAsync(Enums.ReferenceTypes.DeptPaymentTypes))
           .Select(x => new SelectListItem { 
              Text = x.Description, 
              Value = x.Id.ToString() })
            .ToList();

Try to use

model.DeptPaymentTypes = _refDataService.GetAsync(Enums.ReferenceTypes.DeptPaymentTypes).Result
       .Select(x => new SelectListItem { 
          Text = x.Description, 
          Value = x.Id.ToString() })
        .ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM