{"record":{"id":"2910f9e74d5b9e48","repo":"dotnet/efcore","slug":"the-required-column-column-was-not-present-in-2910f9","errorCode":null,"errorMessage":"The required column '{column}' was not present in the results of a 'FromSql' operation.","messagePattern":"The required column '(.+?)' was not present in the results of a 'FromSql' operation\\.","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"error","filePath":"src/EFCore.Relational/Query/Internal/FromSqlQueryingEnumerable.cs","lineNumber":174,"sourceCode":"    ///     This is an internal API that supports the Entity Framework Core infrastructure and not subject to\n    ///     the same compatibility standards as public APIs. It may be changed or removed without notice in\n    ///     any release. You should only use it directly in your code with extreme caution and knowing that\n    ///     doing so can result in application failures when updating to a new Entity Framework Core release.\n    /// </summary>\n    public static int[] BuildIndexMap(IReadOnlyList<string> columnNames, DbDataReader dataReader)\n    {\n        var readerColumns = Enumerable.Range(0, dataReader.FieldCount)\n            .ToDictionary(dataReader.GetName, i => i, StringComparer.OrdinalIgnoreCase);\n\n        var indexMap = new int[columnNames.Count];\n        for (var i = 0; i < columnNames.Count; i++)\n        {\n            var columnName = columnNames[i];\n            if (!readerColumns.TryGetValue(columnName, out var ordinal))\n            {\n                if (columnNames.Count != 1)\n                {\n                    throw new InvalidOperationException(RelationalStrings.FromSqlMissingColumn(columnName));\n                }\n\n                ordinal = 0;\n            }\n\n            indexMap[i] = ordinal;\n        }\n\n        return indexMap;\n    }\n\n    private sealed class Enumerator : IEnumerator<T>\n    {\n        private readonly RelationalQueryContext _relationalQueryContext;\n        private readonly RelationalCommandResolver _relationalCommandResolver;\n        private readonly IReadOnlyList<ReaderColumn?>? _readerColumns;\n        private readonly IReadOnlyList<string> _columnNames;\n        private readonly Func<QueryContext, DbDataReader, int[], T> _shaper;","sourceCodeStart":156,"sourceCodeEnd":192,"githubUrl":"https://github.com/dotnet/efcore/blob/dbf9771522148d61a2467854921bd5dc6f6e6916/src/EFCore.Relational/Query/Internal/FromSqlQueryingEnumerable.cs#L156-L192","documentation":"Thrown by FromSqlQueryingEnumerable.BuildIndexMap when mapping the columns returned by a raw SQL result set to the columns EF expects for entity materialization. EF matches reader columns by name (case-insensitive), so every expected column name must appear in the data reader's output. When a name is missing and more than one column is expected, there is no safe fallback, so EF aborts rather than materialize a partially-null entity. This protects against silent data corruption from column-name mismatches in hand-written SQL.","triggerScenarios":"Calling dbContext.Set<T>().FromSqlRaw(\"SELECT ...\") or FromSqlInterpolated(...) where the raw SQL returns a result set whose column names do not include all the property/column names EF needs. Only fires when columnNames.Count != 1 (the single-column projection case falls back to ordinal 0 at line 177). Triggered when the SQL renames a column (e.g. SELECT Id AS UserId), omits a required column, or returns columns from a different table/shape than the entity.","commonSituations":"Switching a stored procedure or view whose columns were renamed; aliasing columns in raw SQL without matching EF property names; changing the entity model (renaming a property or its column mapping) while leaving old FromSqlRaw strings unchanged; returning a subset of columns from a JOIN in the raw SQL but projecting the full entity.","solutions":["Inspect the exact column name in the error message, then make your FromSqlRaw SQL return a column with that name (use AS aliasing: SELECT user_id AS \"Id\" ...).","Make sure the raw SQL returns ALL columns EF maps for the entity (check the entity's column mappings / [Column] attributes and the migration).","If you intentionally return fewer columns, project into an anonymous type or a non-tracking DTO instead of the full entity, so EF does not expect the missing column.","Enable EF logging / inspect ToQueryString() to compare the expected column set against what your SQL actually returns.","Verify stored procedure / view definitions in the database match what the code assumes (schema drift)."],"exampleFix":"// before - 'LastName' column missing from result set, but EF needs it\nvar users = context.Users.FromSqlRaw(\"SELECT Id, FirstName FROM Users WHERE Active = 1\").ToList();\n\n// after - include every mapped column, aliasing to match EF's expected names\nvar users = context.Users\n    .FromSqlRaw(\"SELECT Id, FirstName, LastName, Email FROM Users WHERE Active = 1\")\n    .ToList();\n\n// or project only what you need into a DTO to avoid requiring all columns\nvar dtos = context.Database.SqlQueryRaw<UserDto>(\n    \"SELECT Id, FirstName FROM Users WHERE Active = 1\").ToList();","handlingStrategy":"validation","validationCode":"// Before calling FromSqlRaw, verify your SQL returns the expected columns by name.\n// Map the entity's expected column names and check against a dry-run reader.\nvar expectedCols = ctx.Model.FindEntityType(typeof(User))!\n    .GetProperties().Select(p => p.GetColumnName()).ToArray();\nusing var probe = ctx.Database.SqlQueryRaw<FormattableString>(userSql).AsAsyncEnumerable()...;\n// Or simply: SELECT the columns and confirm via a one-off schema query:\n// SELECT column_name FROM information_schema.columns WHERE table_name = 'Users'\nforeach (var name in expectedCols)\n    if (!readerColumnNames.Contains(name, StringComparer.OrdinalIgnoreCase))\n        throw new InvalidOperationException($\"FromSqlRaw result is missing column '{name}'\");","typeGuard":null,"tryCatchPattern":"try { var data = ctx.Users.FromSqlRaw(sql).ToList(); }\ncatch (InvalidOperationException ex) when (ex.Message.Contains(\"not present in the results of a\")) {\n    // A mapped column is missing from the raw SQL result set.\n    _logger.LogError(ex, \"FromSqlRaw column mismatch; ensure SQL returns all mapped columns by name.\");\n    throw; // or fall back to a projection DTO\n}","preventionTips":["Keep raw SQL in sync with entity column mappings; add a test that runs the SQL and asserts all expected columns are present.","Prefer FromSqlInterpolated and LINQ composition over wide hand-written SELECT * that may drift from the model.","When changing a property or its column name, grep all FromSqlRaw strings for the old name.","Project into DTOs/anonymous types when you intentionally return fewer columns."],"tags":["ef-core","fromsql","raw-sql","query","schema-mismatch"],"analyzedSha":"dbf9771522148d61a2467854921bd5dc6f6e6916","analyzedAt":"2026-08-06T20:46:03.226Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}