{"record":{"id":"9aff8508d0c9c6c9","repo":"dotnet/efcore","slug":"the-entity-type-entitytype-is-mapped-to-a-sql","errorCode":null,"errorMessage":"The entity type '{entityType}' is mapped to a SQL query, but is derived from '{baseEntityType}'. Derived entity types cannot be mapped to a different SQL query than the base entity type.","messagePattern":"The entity type '(.+?)' is mapped to a SQL query, but is derived from '(.+?)'\\. Derived entity types cannot be mapped to a different SQL query than the base entity type\\.","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"error","filePath":"src/EFCore.Relational/Infrastructure/RelationalModelValidator.cs","lineNumber":336,"sourceCode":"    ///     Validates the SQL query mapping for an entity type.\n    /// </summary>\n    /// <param name=\"entityType\">The entity type to validate.</param>\n    /// <param name=\"logger\">The logger to use.</param>\n    protected virtual void ValidateSqlQuery(\n        IEntityType entityType,\n        IDiagnosticsLogger<DbLoggerCategory.Model.Validation> logger)\n    {\n        var sqlQuery = entityType.GetSqlQuery();\n        if (sqlQuery == null)\n        {\n            return;\n        }\n\n        if (entityType.BaseType != null\n            && (entityType.FindDiscriminatorProperty() == null\n                || sqlQuery != entityType.BaseType.GetSqlQuery()))\n        {\n            throw new InvalidOperationException(\n                RelationalStrings.InvalidMappedSqlQueryDerivedType(\n                    entityType.DisplayName(), entityType.BaseType.DisplayName()));\n        }\n    }\n\n    /// <summary>\n    ///     Validates a single sequence.\n    /// </summary>\n    /// <param name=\"sequence\">The sequence to validate.</param>\n    /// <param name=\"logger\">The logger to use.</param>\n    protected virtual void ValidateSequence(\n        ISequence sequence,\n        IDiagnosticsLogger<DbLoggerCategory.Model.Validation> logger)\n    {\n    }\n\n    /// <summary>\n    ///     Validates a single database function.","sourceCodeStart":318,"sourceCodeEnd":354,"githubUrl":"https://github.com/dotnet/efcore/blob/3a2006ef569de08368d59db5e1468aa8f407e4f8/src/EFCore.Relational/Infrastructure/RelationalModelValidator.cs#L318-L354","documentation":"ValidateSqlQuery throws InvalidMappedSqlQueryDerivedType when an entity type mapped to a SQL query (via ToSqlQuery/ToSqlQueryRaw) has a base type and either lacks a discriminator or its SQL query differs from its base's. Relational mapping requires that a derived entity in a hierarchy share the same defining SQL query as its base — only TPH-over-SQL-query is supported.","triggerScenarios":"Configuring ToSqlQuery(\"SELECT ...\") on a derived entity type; or giving a derived entity a different SQL query string than its base while the hierarchy uses no discriminator. Either condition triggers the throw.","commonSituations":"Trying to use SQL-query mapping (e.g. database views or TVFs) per derived type in a TPT hierarchy; refactoring inheritance and forgetting to remove a ToSqlQuery on the derived type; scaffolding views in an inheritance hierarchy.","solutions":["Define the SQL query only on the hierarchy root entity type and let derived types inherit it.","If using TPH, ensure a discriminator is configured and only the root has ToSqlQuery.","For per-type querying, use separate non-hierarchical entity types or FromSqlRaw on the root with discriminator filtering."],"exampleFix":"// before — derived type has its own SQL query\nmodelBuilder.Entity<Base>().ToSqlQuery(\"SELECT * FROM base_view\");\nmodelBuilder.Entity<Derived>().ToSqlQuery(\"SELECT * FROM derived_view\"); // throws\n\n// after — root owns the SQL query; derived types inherit\nmodelBuilder.Entity<Base>().ToSqlQuery(\"SELECT * FROM base_view\");\nmodelBuilder.Entity<Derived>().HasBase<Base>(); // no ToSqlQuery here","handlingStrategy":"validation","validationCode":"if (entityType.BaseType != null && entityType.GetSqlQuery() is not null\n    && (entityType.FindDiscriminatorProperty() == null\n        || entityType.GetSqlQuery() != entityType.BaseType.GetSqlQuery()))\n    throw new InvalidOperationException(\"Derived entity cannot have a different SQL query than its base.\");","typeGuard":"static bool CanMapToSqlQuery(IEntityType e)\n    => e.BaseType == null\n       || (e.FindDiscriminatorProperty() is not null\n           && e.GetSqlQuery() == e.BaseType?.GetSqlQuery());","tryCatchPattern":null,"preventionTips":["Define ToSqlQuery only on the hierarchy root.","When using TPH with SQL-query mapping, ensure a discriminator is configured.","Avoid mapping derived types to separate views; query the root and filter instead."],"tags":["sql-query-mapping","inheritance","discriminator","model-validation"],"backgroundTag":null,"analyzedSha":"3a2006ef569de08368d59db5e1468aa8f407e4f8","analyzedAt":"2026-08-11T23:42:04.146Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}