{"record":{"id":"098322df7a03c1bd","repo":"dotnet/efcore","slug":"the-replacement-entity-type-entitytype-does-not","errorCode":null,"errorMessage":"The replacement entity type: {entityType} does not have same name and CLR type as entity type this query root represents.","messagePattern":"The replacement entity type: (.+?) does not have same name and CLR type as entity type this query root represents\\.","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"error","filePath":"src/EFCore.Cosmos/Query/Internal/Expressions/FromSqlQueryRootExpression.cs","lineNumber":83,"sourceCode":"    /// <summary>\n    ///     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 override Expression DetachQueryProvider()\n        => new FromSqlQueryRootExpression(EntityType, Sql, Argument);\n\n    /// <summary>\n    ///     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 override EntityQueryRootExpression UpdateEntityType(IEntityType entityType)\n        => entityType.ClrType != EntityType.ClrType\n            || entityType.Name != EntityType.Name\n                ? throw new InvalidOperationException(CoreStrings.QueryRootDifferentEntityType(entityType.DisplayName()))\n                : new FromSqlQueryRootExpression(entityType, Sql, Argument);\n\n    /// <summary>\n    ///     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    protected override Expression VisitChildren(ExpressionVisitor visitor)\n    {\n        var argument = visitor.Visit(Argument);\n\n        return argument != Argument\n            ? new FromSqlQueryRootExpression(EntityType, Sql, argument)\n            : this;\n    }\n\n    /// <summary>","sourceCodeStart":65,"sourceCodeEnd":101,"githubUrl":"https://github.com/dotnet/efcore/blob/dbf9771522148d61a2467854921bd5dc6f6e6916/src/EFCore.Cosmos/Query/Internal/Expressions/FromSqlQueryRootExpression.cs#L65-L101","documentation":"FromSqlQueryRootExpression.UpdateEntityType replaces the entity type backing a FromSqlRaw/FromSqlInterpolated query root during query compilation. It requires the replacement type to have both the same Name and the same ClrType as the original; otherwise it throws InvalidOperationException. This guards the identity contract of a raw-SQL query root.","triggerScenarios":"Combining FromSqlRaw/FromSqlInterpolated with operators (e.g. OfType<T>, casts, or projection rewrites) that cause the pipeline to swap the root's entity type for one whose CLR type or model Name differs.","commonSituations":"Calling OfType<DerivedType>() on a FromSqlRaw query where DerivedType is not the same identity as the root entity; mixing raw SQL roots with inheritance hierarchies; upgrading EF Core and hitting a changed rewrite path.","solutions":["Issue FromSqlRaw against the DbSet of the exact entity type you intend to query and avoid OfType/casts that change entity identity.","If you need a derived view, write the SQL against that entity's container and call FromSqlRaw on its DbSet.","Project into a DTO via Select instead of changing the query root's entity type."],"exampleFix":"// before\nvar orders = ctx.Set<BaseOrder>()\n    .FromSqlRaw(\"SELECT * FROM c\")\n    .OfType<SpecialOrder>(); // throws if identity differs\n\n// after\nvar orders = ctx.Set<SpecialOrder>()\n    .FromSqlRaw(\"SELECT * FROM c WHERE c.Discriminator = 'SpecialOrder'\");","handlingStrategy":"validation","validationCode":"// Ensure OfType/cast target shares Name + ClrType with the FromSql root.\nvar root = cosmosModel.FindEntityType(typeof(BaseOrder))!;\nvar target = cosmosModel.FindEntityType(typeof(T))!;\nif (root.Name != target.Name || root.ClrType != target.ClrType)\n    throw new InvalidOperationException(\"OfType target must match FromSql root identity.\");","typeGuard":"static bool IsSameQueryRootIdentity(IEntityType a, IEntityType b)\n    => a.Name == b.Name && a.ClrType == b.ClrType;","tryCatchPattern":"try { var q = ctx.Set<BaseOrder>().FromSqlRaw(sql).ToList(); }\ncatch (InvalidOperationException ex) when (ex.Message.Contains(\"does not have same name and CLR type\"))\n{ /* reissue FromSqlRaw on the correct DbSet */ }","preventionTips":["Always call FromSqlRaw on the DbSet of the entity your SQL returns.","Avoid OfType<>() after FromSqlRaw unless the type is the same identity.","Document raw-SQL roots in integration tests."],"tags":["cosmos","fromsql","entity-type","query-root"],"analyzedSha":"dbf9771522148d61a2467854921bd5dc6f6e6916","analyzedAt":"2026-08-06T20:46:03.226Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}