EF Core - System.InvalidOperationException : The required column 'Id' was not present in the results of a 'FromSql' operation.
Yesterday I talked about an error I got when using the FromSql
method in Entity Framework Core(EF Core). It allows you to execute raw SQL queries against a relational database. Here is the example I was using yesterday:
Remark: The FromSql
method was introduced in EF Core 7.0. In older versions, you should use FromSqlInterpolated
instead.
However when we tried to execute the code above it failed with the following error message:
System.InvalidOperationException : The required column 'Id' was not present in the results of a 'FromSql' operation.
You typically get the error message above when there isn’t a matching column found in the SQL result for every property in your entity type.
In our case the query was using a ‘SELECT *’ so I couldn’t be that we missed a column. To explain what was causing the issue, I first have to show our entity type and mapping class:
As you can see there is a difference between the name of one of our columns(ProductID) and the property (Id). When you are using the LINQ syntax to query your data, EF Core will correctly translate between the two. However when you try to use the FromSql
method, it will not use the mapping configuration and the returned column names should perfectly match with the property names.
To fix it, I updated the query to return an Id column: