调用 'DbSet<>.Find' 的位置 0 的键值是 'string' 类型,与 'long?' 的 属性 类型不匹配

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?'

我有路由问题,我想我知道答案,但我无法让它工作。

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;
        }

我认为问题出在 api/Shippingschedules/name 方法中,它给我这个错误:

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?'

FindAsync(name) 期待 long 而不是 string

我想我需要用其他东西替换 FindAsync(),比如 where<> 或 SQL?我是 LINQ 的新手,一般来说 API。

会不会也是我没有定义Mappings?在我的 Program.cs 中,我只有如图所示

app.MapControllers();

谢谢

我认为这实际上是一个路由命名问题。除非您在其他地方这样做,否则按名称获取 ShippingSchedules 的途径是“api/Shippingschedules/GetShippingscheduleByName”

端点“api/Shippingschedules/name”与您接受 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;
        }

此外,属性似乎需要一个 int,而参数是一个 long。我认为这也可以得到清理。

希望这能解决问题![​​=11=]

我认为发生此错误是因为实体 Shippingschedules 的主键具有数据类型 long,但您传递了 字符串.

FindAsync() 方法将对象的主键作为输入。 您可以使用:

await _context.Shippingschedules.Where(x => x.name.Contains(name)).FirstOrDefault();