实体框架核心linq查询返回InvalidCastException [英] Entity Framework Core linq query returns InvalidCastException

查看:86
本文介绍了实体框架核心linq查询返回InvalidCastException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用Entity Framework在.net CORE中创建一个Web api.

I am currently creating a web api in .net CORE with Entity Framework.

每当我尝试使用linq通过ID选择单个记录时,都会出现以下错误:

Whenever I try to select a single record by ID with linq, I get the following error:

类型为"System.InvalidCastException"的异常发生在 Microsoft.EntityFrameworkCore.dll,但未在用户代码中处理.

An exception of type 'System.InvalidCastException' occurred in Microsoft.EntityFrameworkCore.dll but was not handled in user code.

其他信息:无法转换类型为'System.Int32'的对象 键入"System.Char".

Additional information: Unable to cast object of type 'System.Int32' to type 'System.Char'.

每当我执行以下linq查询时,就会发生此错误:

This error happens whenever I execute the following linq query:

int id = 1;
User user = context.Users.First(i => i.UserId == id);

我已经检查过,并且字段UserId和变量id都是整数.该表还包含足够的元素,并且存在id为1的行.

I have already checked, and both field UserId and variable id are integers. Also the table contains enough elements and a row with an id of 1 exists.

有人可以告诉我我在做什么错吗?

Can anybody tell me what I'm doing wrong here?

这是User模型的一部分:

public class User
{
    public int UserId { get; set; }
    (...)
}

推荐答案

注意:答案实际上是在原始问题下的注释中提供的.我只是在这里添加一些内容,以使其更清晰可见.

Entity Framework显然通过代表每个表中各个列的属性将C#类映射到数据库表.现在,如果这些属性之一的数据类型与数据库中其对应列的数据类型不兼容,那么即使尝试从该表中获取任何内容,即使不直接涉及不匹配属性,您也会得到System.InvalidCastException查找.

Entity Framework obviously maps C# classes to database tables via properties that represent the various columns in each table. Now if the datatype of one of these properties is not compatible with the datatype of it's corresponding column in the database, then you will get an System.InvalidCastException when attempting to fetch anything from that table, even if the mismatching property is not directly involved in the look-up.

在问题中,查询为:

User user = context.Users.First(i => i.UserId == id);

id及其对应的属性UserId在这里都有效且彼此兼容并不重要,因为所获取的是整个类User的实例.

It does not matter that both id and it's corresponding property UserId are valid and compatible with each other here, because what is being fetched is an instance of the whole class User.

显然,User中某些其他属性的类型与数据库中user表中具有相同名称的列的类型不兼容,因此尝试映射到该列会引发上述异常.

Apparently the type of some other property in User is incompatible with the type a column with the same name in the user table in the database, and so the attempt to map to it throws the above exception.

这篇关于实体框架核心linq查询返回InvalidCastException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆