我目前正在使用实体框架在.net CORE中创建一个web api。实体框架核心linq查询返回InvalidCastException
每当我试着通过ID与LINQ选择一个记录,我得到以下错误:
An exception of type 'System.InvalidCastException' occurred in Microsoft.EntityFrameworkCore.dll but was not handled in user code.
Additional information: Unable to cast object of type 'System.Int32' to type 'System.Char'.
这个错误发生,每当我执行以下LINQ查询:
int id = 1;
User user = context.Users.First(i => i.UserId == id);
我有已经检查过,并且字段UserId
和变量id
都是整数。此外,该表格包含足够的元素,并且存在1行id
。
有人能告诉我我在做什么错吗?
编辑:这里是User
模型的一部分:
public class User
{
public int UserId { get; set; }
(...)
}
我不认为问题中有足够的信息还没有让这个问题得到解答。至少,表格定义和类定义也是需要的。 – hvd
尝试使用i.UserId.Equals(id)代替i.UserId == id –
@hvd我添加了'User'模型的一部分。 – Max