Entity Framework Core linq query returns InvalidCastException

.net-core asp.net-core c# entity-framework-core linq

Question

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; }
    (...)
}
1
2
2/15/2018 10:23:43 PM

Accepted Answer

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.

2
2/15/2018 9:42:34 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow