I am having Routing issues, and I think I know the answer, but I cannot get this to work.
namespace POTSwebAPI.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class ShippingschedulesController : ControllerBase
{
private readonly POTScontext _context;
public ShippingschedulesController(POTScontext context)
{
_context = context;
}
// GET: api/Shippingschedules
[HttpGet]
public async Task<ActionResult<IEnumerable<Shippingschedule>>> GetShippingschedules()
{
return await _context.Shippingschedules.ToListAsync();
}
// GET: api/Shippingschedules/ID
[HttpGet("{id:int}")]
public async Task<ActionResult<Shippingschedule>> GetShippingschedule(long? id)
{
ActionResult<Shippingschedule> Shippingschedule = await _context.Shippingschedules.FindAsync(id);
if (Shippingschedule == null)
{
return NotFound();
}
return Shippingschedule;
}
// GET: api/Shippingschedules/name
[HttpGet("{name}")]
public async Task<ActionResult<Shippingschedule>> GetShippingscheduleByName(string name)
{
ActionResult<Shippingschedule> Shippingschedule = await _context.Shippingschedules.FindAsync(name); //<-- I think the problem is here, as it's expecting an "long" not a "string"?
if (Shippingschedule == null)
{
return NotFound();
}
return Shippingschedule;
}
I think the problem is in the api/Shippingschedules/name
method, which gives me this error:
The key value at position 0 of the call to 'DbSet<>.Find' was of type 'string', which does not match the property type of 'long?'
The FindAsync(name)
is expecting a long
and not a string
?
I am thinking I need to replace FindAsync() with something else, like a where<> or SQL? I am new to LINQ and API in general.
Could it also be that I've not defined the Mappings? In my Program.cs, I have this only as is shown
app.MapControllers();
Thanks
CodePudding user response:
This is actually a route naming issue I think. Unless you are doing it somewhere else, the route to get your ShippingSchedules by name is "api/Shippingschedules/GetShippingscheduleByName"
The endpoint "api/Shippingschedules/name" more closely matches your endpoint that is accepting a long.
[HttpGet("{id:int}")]
public async Task<ActionResult<Shippingschedule>> GetShippingschedule(long? id)
{
ActionResult<Shippingschedule> Shippingschedule = await _context.Shippingschedules.FindAsync(id);
if (Shippingschedule == null)
{
return NotFound();
}
return Shippingschedule;
}
Also the attribute seems to expect an int there, while the parameter is a long. I think that can get cleared up too.
Hopefully this fixes it!
CodePudding user response:
I think this error occurs because the primary key of entity Shippingschedules has data type long, but you passed string.
The method FindAsync() takes as an input the primary key of the object. You can use:
await _context.Shippingschedules.Where(x => x.name.Contains(name)).FirstOrDefault();
Goodluck!