dotnet / dotnet/efcore

Sealed entity types lead to error and warning when trying to cast to IInjectableService in precompiled queries

Open
#37,957 1 comment 0 reactions 0 assignees View on GitHub
area-precompiled-queries customer-reported
Dominant language
C#
Stars
14.8k
Forks
3.4k
PR merge metrics
PR metrics pending

Description

### Bug description

Generated code for precompiled queries contains casts to `IInjectableService` like this:

```
if (instance is IInjectableService)
{
((IInjectableService)instance).Injected(materializationContext1.Context, instance, QueryTrackingBehavior.TrackAll, blogEntityType0);
}
```

When type of `instance` variable is sealed and isn't implementing `IInjectableService`, the compiler deduces that the cast will always fail, and gives:

```
/workspaces/ef-play/badcast/Generated/Program.EFInterceptors.Context.cs(77,21): warning CS0184: The given expression is never of the provided ('IInjectableService') type
/workspaces/ef-play/badcast/Generated/Program.EFInterceptors.Context.cs(79,22): error CS0030: Cannot convert type 'Blog' to 'Microsoft.EntityFrameworkCore.Internal.IInjectableService'
```

The workaround is to remove sealed modifier from the entity type.

See attached project with minimal example.

Can be reproduced with:

```
> dotnet publish --ucr --sc
```

Or

```
> dotnet ef dbcontext optimize --output-dir Generated --nativeaot --precompile-queries --verbose
> dotnet build
```

[badcast.zip](https://github.com/user-attachments/files/26112949/badcast.zip)

### Your code

```csharp
See attached project.
```

### Stack traces

```text

```

### Verbose output

```text

```

### EF Core version

10.0.3, 11.0.0-preview.2.26159.112

### Database provider

Microsoft.EntityFrameworkCore.Sqlite

### Target framework

.NET 10, .NET 11

### Operating system

Ubuntu 24.04.4 LTS

### IDE

_No response_

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.