Skip to content

ToString() on a string expression fails to translate (“Translation of method ‘object.ToString’ failed”) #4046

Closed

Description

@tamasprincz97-dot

Description

Calling ToString() on a string-typed expression throws when EF must translate it to SQL. The common real-world case is a dynamic GroupBy whose key is typed as object, where the key is later used in Where or OrderBy. The same query works when the key is an int.

Repro

public class Blog
{
    public int Id { get; set; }
    public string Name { get; set; } = "";
}

// 1. Plain string column
await ctx.Blogs.Where(b => b.Name.ToString() == "foo").ToListAsync();

// 2. Grouping key typed as object (e.g. picked by a switch over grouping options)
await ctx.Blogs
    .GroupBy(b => (object)b.Name)
    .Select(g => new { Key = g.Key.ToString(), Count = g.Count() })
    .OrderBy(x => x.Key)   // same with .Where(x => x.Key == "foo")
    .ToListAsync();

Actual

System.InvalidOperationException: The LINQ expression '...' could not be translated. Additional information: Translation of method 'object.ToString' failed. ...

If the grouping key is (object)b.Id, the query translates to ORDER BY COALESCE(b."Id"::text, '').

Expected

The string expression is used as is, for example HAVING b."Name" = 'foo' or ORDER BY b."Name".

Cause

NpgsqlObjectToStringTranslator has no case for string-mapped instances, so it returns null. EF removes the (object) convert from the grouping key, so the translator receives the plain text column. The SQL Server and SQLite translators handle this case:

if (instance.TypeMapping?.ClrType == typeof(string))
{
    return instance;
}

Workaround

Order by the grouping key before projecting, for example .GroupBy(...).OrderBy(g => g.Key).Select(...), or avoid ToString() on string keys.

Versions

  • Npgsql.EntityFrameworkCore.PostgreSQL 10.0.2 with EF Core 10.0.9
  • Also reproduced on main (ad93dab4, EF Core 11.0.0-rc.2)
  • PostgreSQL 18

I have a fix with tests ready and will open a PR.

Activity

  1. roji commented on Oct 20, 2026

    @roji
    Member

    AI Triage

    The below is an AI-generated analysis and may contain inaccuracies.

    Confirmed: this is a PostgreSQL-provider bug, not an upstream EF Core bug. An independent console repro reproduces all three reported failure cases: Name.ToString() in Where, and the object-typed string grouping key followed by either OrderBy or Where.

    The failure occurs during ToQueryString(), before any database connection is opened, so neither PostgreSQL 18 nor seed data is necessary.

    Versions and regression

    All three failure cases throw InvalidOperationException with Translation of method 'object.ToString' failed in each tested combination:

    Npgsql.EntityFrameworkCore.PostgreSQL EF Core Result
    8.0.0 8.0.0 Fails
    8.0.11 8.0.32 Fails
    9.0.4 9.0.21 Fails
    10.0.2 10.0.9 Fails
    10.0.3 10.0.13 Fails

    This is a longstanding gap, present since at least 8.0.0, rather than a new 10.0 regression. No previously working version was identified among those tested.

    Provider comparison and cause

    With EF Core 10.0.9, both SQL Server and SQLite successfully translate all three queries. Their string grouping variants generate ORDER BY or HAVING directly over the string column.

    The reported cause matches the source: NpgsqlObjectToStringTranslator neither handles string instances separately nor includes them in its supported types. In contrast, the SQL Server and SQLite translators return the instance unchanged when its type mapping's CLR type is string.

    The integer grouping variant and the suggested workaround of ordering before projecting also translate successfully with Npgsql 10.0.2 / EF Core 10.0.9.

    Duplicate search

    The closest upstream match is dotnet/efcore#20839, “Translate ToString() on a string column,” closed as completed with milestone 8.0.0. It describes the same missing translation in SQL Server, but does not resolve the PostgreSQL-provider gap, so this issue should remain here.

    dotnet/efcore#12824 is an older related report, closed after the reporter could no longer reproduce it. No matching existing PostgreSQL-provider issue was found.

    minimal repro

    Repro.csproj:

    <Project Sdk="Microsoft.NET.Sdk">
      <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>net10.0</TargetFramework>
        <Nullable>enable</Nullable>
        <ImplicitUsings>enable</ImplicitUsings>
      </PropertyGroup>
      <ItemGroup>
        <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.2" />
        <PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="10.0.9" />
      </ItemGroup>
    </Project>

    Program.cs:

    using Microsoft.EntityFrameworkCore;
    using Microsoft.Extensions.Logging;
    
    await using var context = new TestContext();
    
    Console.WriteLine(context.Blogs.Where(b => b.Name.ToString() == "foo").ToQueryString());
    
    public class TestContext : DbContext
    {
        public DbSet<Blog> Blogs { get; set; }
    
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            => optionsBuilder
                .UseNpgsql("Host=localhost;Database=repro4046;Username=unused;Password=unused")
                .LogTo(Console.WriteLine, LogLevel.Information)
                .EnableSensitiveDataLogging();
    }
    
    public class Blog
    {
        public int Id { get; set; }
        public string Name { get; set; } = "";
    }

    Run with dotnet run. No running database is needed; query translation throws the reported exception.

  2. added theissue type on Oct 20, 2026
  3. self-assigned this
    on Oct 20, 2026
  4. added this to the 10.0.4 milestone on Oct 20, 2026
  5. linked a pull request that will close this issue[9.0] Translate ToString on string expressions #4051on Oct 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions