Max
Max

Reputation: 2524

Entity Framework Core linq query returns InvalidCastException

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

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

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

This error happens whenever I execute the following linq query:

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

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?

EDIT: Here is a part of the User Model:

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

Upvotes: 5

Views: 10812

Answers (1)

Kjartan
Kjartan

Reputation: 19111

Note: The answer was actually provided in a comment under the original question. I'm just adding a little to it here, to make it more visible and clear.


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.

In the question, the query was:

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

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.

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.

Upvotes: 6

Related Questions