1

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

1 Answer 1

2

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;
        }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.