我目前正在使用實體框架在.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