Entity Framework 核心 linq 查询 returns InvalidCastException
Entity Framework Core linq query returns InvalidCastException
我目前正在使用 Entity Framework.
在 .net CORE 中创建网站 api
每当我尝试使用 linq 按 ID select 单个记录时,我都会收到以下错误:
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
都是整数。此外,table 包含足够的元素,并且存在 id
为 1 的行。
谁能告诉我我做错了什么?
编辑:这是 User
模型的一部分:
public class User
{
public int UserId { get; set; }
(...)
}
注意:答案实际上是在原问题下的评论中提供的。我只是在这里添加了一点,使其更加明显和清晰。
Entity Framework 显然通过表示每个 table 中的各个列的属性将 C# classes 映射到数据库 tables。现在,如果这些属性之一的数据类型与它在数据库中对应列的数据类型不兼容,那么当您尝试从 table 中获取任何内容时,您将得到一个 System.InvalidCastException
,即使不匹配属性 不直接参与查找。
在问题中,查询是:
User user = context.Users.First(i => i.UserId == id);
这里 id
和它对应的 属性 UserId
都是有效的并且彼此兼容并不重要,因为正在获取的是整个 class User
。
显然 User
中某些其他 属性 的类型与数据库中 user
table 中具有相同名称的列的类型不兼容,并且因此尝试映射到它会引发上述异常。
我目前正在使用 Entity Framework.
在 .net CORE 中创建网站 api每当我尝试使用 linq 按 ID select 单个记录时,我都会收到以下错误:
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
都是整数。此外,table 包含足够的元素,并且存在 id
为 1 的行。
谁能告诉我我做错了什么?
编辑:这是 User
模型的一部分:
public class User
{
public int UserId { get; set; }
(...)
}
注意:答案实际上是在原问题下的评论中提供的。我只是在这里添加了一点,使其更加明显和清晰。
Entity Framework 显然通过表示每个 table 中的各个列的属性将 C# classes 映射到数据库 tables。现在,如果这些属性之一的数据类型与它在数据库中对应列的数据类型不兼容,那么当您尝试从 table 中获取任何内容时,您将得到一个 System.InvalidCastException
,即使不匹配属性 不直接参与查找。
在问题中,查询是:
User user = context.Users.First(i => i.UserId == id);
这里 id
和它对应的 属性 UserId
都是有效的并且彼此兼容并不重要,因为正在获取的是整个 class User
。
显然 User
中某些其他 属性 的类型与数据库中 user
table 中具有相同名称的列的类型不兼容,并且因此尝试映射到它会引发上述异常。