{"record":{"id":"2badd21465ecd79a","repo":"dotnet/efcore","slug":"sqlqueryunmappedtype","errorCode":"SqlQueryUnmappedType","errorMessage":"The element type '{elementType}' used in 'SqlQuery' method is not natively supported by your database provider. Either use a supported element type, or use ModelConfigurationBuilder.DefaultTypeMapping to define a mapping for your type.","messagePattern":"The element type '(.+?)' used in 'SqlQuery' method is not natively supported by your database provider\\. Either use a supported element type, or use ModelConfigurationBuilder\\.DefaultTypeMapping to define a mapping for your type\\.","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"error","filePath":"src/EFCore.Relational/Query/RelationalQueryableMethodTranslatingExpressionVisitor.cs","lineNumber":222,"sourceCode":"                Check.DebugAssert(\n                    !subquerySourceSelectExpression.HasNonEntityNullabilityMarkers,\n                    \"Non-grouping subquery clone carries a live non-entity nullability marker; it would be stranded by Clone(). \"\n                    + \"Route it through a marker-aware remap as the GroupByShaperExpression case does.\");\n\n                var clonedSelectExpression = subquerySourceSelectExpression.Clone();\n                return new ShapedQueryExpression(\n                    clonedSelectExpression,\n                    new QueryExpressionReplacingExpressionVisitor(shapedQueryExpression.QueryExpression, clonedSelectExpression)\n                        .Visit(shapedQueryExpression.ShaperExpression));\n\n            case SqlQueryRootExpression sqlQueryRootExpression:\n            {\n                var typeMapping = RelationalDependencies.TypeMappingSource.FindMapping(\n                    sqlQueryRootExpression.ElementType, RelationalDependencies.Model);\n\n                if (typeMapping == null)\n                {\n                    throw new InvalidOperationException(\n                        RelationalStrings.SqlQueryUnmappedType(sqlQueryRootExpression.ElementType.DisplayName()));\n                }\n\n                var alias = _sqlAliasManager.GenerateTableAlias(\"sql\");\n                var selectExpression = new SelectExpression(\n                    [new FromSqlExpression(alias, sqlQueryRootExpression.Sql, sqlQueryRootExpression.Argument)],\n                    new ColumnExpression(\n                        SqlQuerySingleColumnAlias,\n                        alias,\n                        sqlQueryRootExpression.Type.UnwrapNullableType(),\n                        typeMapping,\n                        sqlQueryRootExpression.Type.IsNullableType()),\n                    identifier: [],\n                    _sqlAliasManager);\n\n                Expression shaperExpression = new ProjectionBindingExpression(\n                    selectExpression, new ProjectionMember(), sqlQueryRootExpression.ElementType.MakeNullable());\n","sourceCodeStart":204,"sourceCodeEnd":240,"githubUrl":"https://github.com/dotnet/efcore/blob/dbf9771522148d61a2467854921bd5dc6f6e6916/src/EFCore.Relational/Query/RelationalQueryableMethodTranslatingExpressionVisitor.cs#L204-L240","documentation":"In the SqlQueryRootExpression case (line 215-251), EF looks up a relational type mapping for the element type via the type mapping source. Raw SQL queries (SqlQueryRaw/SqlQuery<T>) require each element to be a type the provider can map to a single column. If FindMapping returns null, SqlQueryUnmappedType is thrown, suggesting DefaultTypeMapping configuration.","triggerScenarios":"Calling context.Database.SqlQueryRaw<T>(sql) or SqlQuery<T>(sql) where T is not a natively supported primitive (int, string, DateTime, etc.) and has no configured mapping — e.g. a custom struct, a complex object, or an unmapped enum.","commonSituations":"Using SqlQuery<T> with a custom value type or DTO that the provider does not know how to read from a single result column; forgetting that SqlQuery<T> maps T to one column (unlike entity queries); provider that lacks a mapping for an uncommon primitive (e.g. some numeric/decimal variants).","solutions":["Use a natively supported primitive type (int, long, string, Guid, DateTime, decimal, etc.) as the element type.","Register a mapping for your custom type via ModelConfigurationBuilder.DefaultTypeMapping<T>() in OnModelCreating/Configure.","Map the result to an entity type and query the DbSet instead, or project scalar columns separately."],"exampleFix":"// before (custom struct has no mapping)\nvar ids = db.Database.SqlQueryRaw<MyCustomId>(\"SELECT id FROM t\");\n\n// after (use a supported primitive, or register a mapping)\nvar ids = db.Database.SqlQueryRaw<int>(\"SELECT id FROM t\");\n// or, in model configuration:\n// configurationBuilder.DefaultTypeMapping<MyCustomId>();","handlingStrategy":"validation","validationCode":"// Confirm the element type has a relational mapping before calling SqlQuery<T>.\nvar mapping = db.GetService<IRelationalTypeMappingSource>().FindMapping(typeof(T));\nif (mapping is null) throw new InvalidOperationException($\"No mapping for {typeof(T)}; use a primitive or register DefaultTypeMapping.\");","typeGuard":"// Restrict SqlQuery element types to provider-supported primitives at compile time.\nstatic bool IsSupportedElementType(Type t) =>\n    t == typeof(int) || t == typeof(long) || t == typeof(string)\n    || t == typeof(Guid) || t == typeof(DateTime) || t == typeof(decimal)\n    || t == typeof(double) || t == typeof(bool);","tryCatchPattern":"try { var rows = await db.Database.SqlQueryRaw<T>(sql).ToListAsync(); }\ncatch (InvalidOperationException ex) when (ex.Message.Contains(\"not natively supported\"))\n{ /* switch T to a primitive, or register DefaultTypeMapping<T> */ }","preventionTips":["Use primitive scalar types as SqlQuery<T> element types.","Register custom types via ModelConfigurationBuilder.DefaultTypeMapping<T>.","Remember SqlQuery<T> maps T to a single column; query entities via DbSet for multi-column results."],"tags":["efcore","sqlquery","type-mapping","raw-sql"],"analyzedSha":"dbf9771522148d61a2467854921bd5dc6f6e6916","analyzedAt":"2026-08-06T20:46:03.226Z","schemaVersion":2},"datasetVersion":"2026-08-07T02:17:10.218Z"}