Home > Enterprise >  Cannot implicitly convert type 'System.Collections.Generic.List<>' to 'Microsof
Cannot implicitly convert type 'System.Collections.Generic.List<>' to 'Microsof

Time:04-14

I cannot seem to get past this error in my ASP.net Core 6 API web app.

My httpget()

 // GET: api/Shippingschedules/shipname
        [HttpGet("{shipname}")]
        public async Task<ActionResult<Shippingschedule>> GetShippingSchedulesByShip(string shipname)
        {
            ActionResult<Shippingschedule> Shippingschedule = await _context.Shippingschedules.Where(
                x => x.Text.Contains(shipname)).ToListAsync(); //.FirstOrDefaultAsync();

            if (Shippingschedule == null)
            {
                return NotFound();
            }

            return Shippingschedule;
        }

But if replace the ToListAsync() to the FirstOrDefaultAsync(), it compiles. Why?

I am trying to bring back all the records it finds, not just the first one. What am I doing wrong?

Thanks

CodePudding user response:

The FirstOrDefaultAsync() works because it returns only one record where as ToListAsync() returns a collection of the record.

Change the ActionResult<Shippingschedule> to IEnumerable<ShippingSchedule> and the .ToListAsync() should work. Also, change the return type of api from Task<ActionResult<Shippingschedule>> to Task<ActionResult<IEnumerable<Shippingschedule>>>

        [HttpGet("{shipname}")]
        public async Task<ActionResult<IEnumerable<Shippingschedule>>> GetShippingSchedulesByShip(string shipname)
        {
            IEnumerable<ShippingSchedule> Shippingschedule = await _context.Shippingschedules.Where(
                x => x.Text.Contains(shipname)).ToListAsync(); //.FirstOrDefaultAsync();

            if (Shippingschedule == null)
            {
                return NotFound();
            }

            return Shippingschedule;
        }
  • Related