Skip to content

Right/LeftJoin throws with inner being a string collection #3787

Closed as duplicate

Description

@WhatzGames

Bug Report

Initial Goal

I was trying to write a query using the new RightJoin operation, to see what string values in a collection are not contained within a table.

Observed Behavior

Running the query with integers or with SQLite works without any issue.
Using a string collection always ends up throwing an exception though.
Simply switching RightJoin for LeftJoin causes the same exception to occur.

Minimal Repro
using Microsoft.EntityFrameworkCore;


await using var db = new DemoDbContext();
await db.Database.EnsureDeletedAsync();
await db.Database.EnsureCreatedAsync();

db.Blogs.Add(new Blog { AlternateKey = "abc"});
db.Blogs.Add(new Blog { AlternateKey = "ghi"});
await db.SaveChangesAsync();

string[] values = ["abc", "def", "ghi"];

await db.Blogs
    .RightJoin(values, blog => blog.AlternateKey, value => value,
        (blog, missingValue) => new { Blog = blog, MissingValue = missingValue })
    .Where(x => x.Blog == null)
    .Select(x => x.MissingValue)
    .ForEachAsync(Console.WriteLine);

/* using integers works
int[] values = [1, 2, 3];

await db.Blogs
    .RightJoin(values, blog => blog.Id, value => value,
        (blog, missingValue) => new { Blog = blog, MissingValue = missingValue })
    .Where(x => x.Blog == null)
    .Select(x => x.MissingValue)
    .ForEachAsync(Console.WriteLine);
*/

internal sealed class DemoDbContext : DbContext
{
    private const string SQLiteConnectionString = "";
    private const string PostgresConnectionString = "";
    public DbSet<Blog> Blogs => Set<Blog>();

    protected override void OnConfiguring(DbContextOptionsBuilder options)
        => options
            .LogTo(Console.WriteLine)
            //.UseSqlite(SQLiteConnectionString)
            .UseNpgsql(PostgresConnectionString)
            ;

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Blog>(builder =>
        {
            builder.HasKey(x => x.Id);
            builder.Property(x => x.AlternateKey)
                .HasMaxLength(3);
        });
    }
}

internal sealed class Blog
{
    public int Id { get; set; }
    public required string AlternateKey { get; set; }
}
Stacktrace
System.InvalidOperationException: Conflicting type mappings were inferred for column 'value'.
   at Microsoft.EntityFrameworkCore.Query.RelationalTypeMappingPostprocessor.TryGetInferredTypeMapping(String tableAlias, String columnName, RelationalTypeMapping& inferredTypeMapping)
   at Npgsql.EntityFrameworkCore.PostgreSQL.Query.Internal.NpgsqlTypeMappingPostprocessor.VisitExtension(Expression expression)
   at Microsoft.EntityFrameworkCore.Query.SqlExpressions.PredicateJoinExpressionBase.VisitChildren(ExpressionVisitor visitor)
   at Microsoft.EntityFrameworkCore.Query.RelationalTypeMappingPostprocessor.VisitExtension(Expression expression)
   at Npgsql.EntityFrameworkCore.PostgreSQL.Query.Internal.NpgsqlTypeMappingPostprocessor.VisitExtension(Expression expression)
   at Microsoft.EntityFrameworkCore.Query.SqlExpressions.SelectExpression.<VisitChildren>g__VisitList|127_0[T](List`1 list, Boolean inPlace, Boolean& changed, <>c__DisplayClass127_0&)
   at Microsoft.EntityFrameworkCore.Query.SqlExpressions.SelectExpression.VisitChildren(ExpressionVisitor visitor)
   at Microsoft.EntityFrameworkCore.Query.RelationalTypeMappingPostprocessor.VisitExtension(Expression expression)
   at Npgsql.EntityFrameworkCore.PostgreSQL.Query.Internal.NpgsqlTypeMappingPostprocessor.VisitExtension(Expression expression)
   at Microsoft.EntityFrameworkCore.Query.RelationalTypeMappingPostprocessor.VisitExtension(Expression expression)
   at Npgsql.EntityFrameworkCore.PostgreSQL.Query.Internal.NpgsqlTypeMappingPostprocessor.VisitExtension(Expression expression)
   at Microsoft.EntityFrameworkCore.Query.RelationalTypeMappingPostprocessor.Process(Expression expression)
   at Npgsql.EntityFrameworkCore.PostgreSQL.Query.Internal.NpgsqlQueryTranslationPostprocessor.ProcessTypeMappings(Expression expression)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryTranslationPostprocessor.Process(Expression query)
   at Npgsql.EntityFrameworkCore.PostgreSQL.Query.Internal.NpgsqlQueryTranslationPostprocessor.Process(Expression query)
   at Microsoft.EntityFrameworkCore.Query.QueryCompilationContext.CreateQueryExecutorExpression[TResult](Expression query)
   at Microsoft.EntityFrameworkCore.Query.QueryCompilationContext.CreateQueryExecutor[TResult](Expression query)
   at Microsoft.EntityFrameworkCore.Storage.Database.CompileQuery[TResult](Expression query, Boolean async)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.CompileQueryCore[TResult](IDatabase database, Expression query, IModel model, Boolean async)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass11_0`1.<ExecuteCore>b__0()
   at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQuery[TResult](Object cacheKey, Func`1 compiler)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.ExecuteCore[TResult](Expression query, Boolean async, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.ExecuteAsync[TResult](Expression query, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.ExecuteAsync[TResult](Expression expression, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1.GetAsyncEnumerator(CancellationToken cancellationToken)
   at System.Runtime.CompilerServices.ConfiguredCancelableAsyncEnumerable`1.GetAsyncEnumerator()
   at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ForEachAsync[T](IQueryable`1 source, Action`1 action, CancellationToken cancellationToken)
   at Program.<Main>$(String[] args) in /Users/obedkooijman/RiderProjects/Test/Test/Program.cs:line 14
   at Program.<Main>$(String[] args) in /Users/obedkooijman/RiderProjects/Test/Test/Program.cs:line 14
   at Program.<Main>(String[] args)

Expected Behavior

LINQ correctly translates to

SELECT p.value
FROM "Blogs" AS b
RIGHT JOIN unnest(@p) AS p(value) ON b."AlternateKey" = p.value
WHERE b."Id" IS NULL;

Dependencies

Package Version
Npgsql.EntityFrameworkCore.PostgreSQL 10.0.1
Microsoft.EntityFrameworkCore.Sqlite 10.0.5

Activity

  1. roji commented on Mar 18, 2026

    @roji
    Member

    AI Triage

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

    Summary

    Confirmed bug. The RightJoin (and LeftJoin, and even regular Join) with a string in-memory collection throws System.InvalidOperationException: Conflicting type mappings were inferred for column 'Value' when the joined string property has a non-default type mapping such as HasMaxLength() or HasColumnType().

    Root cause: The ValuesExpression generated for the in-memory string collection gets one type mapping (e.g. nvarchar(max)), while the entity property brings in a different type mapping (e.g. nvarchar(3) from HasMaxLength(3)), causing a conflict in RelationalTypeMappingPostprocessor.TryGetInferredTypeMapping.

    Key observations:

    • Reproduces on SQL Server (not Npgsql-specific) — this is a general EF Core bug.
    • Joining on int collections works fine (no type mapping conflict).
    • Removing HasMaxLength makes the string join work.
    • LeftJoin and regular Join with an in-memory string collection also fail with the same error.
    • The user mentions SQLite works — this is because SQLite doesn't have the same type mapping infrastructure.

    Duplicate

    This appears to be a duplicate of (or closely related to) dotnet/efcore#31776 — "Collection type inference fails with conflicting mappings in some cases when a non-default mapping is used", which tracks the same Conflicting type mappings error with ValuesExpression when a string property has [MaxLength]/HasMaxLength. That issue is still open and in the Backlog.

    Minimal repro

    Test.csproj:

    <Project Sdk="Microsoft.NET.Sdk">
      <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>net10.0</TargetFramework>
      </PropertyGroup>
      <ItemGroup>
        <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="10.0.5" />
      </ItemGroup>
    </Project>

    Program.cs:

    using System.Linq;
    using System;
    using Microsoft.EntityFrameworkCore;
    using Microsoft.Extensions.Logging;
    
    await using var db = new TestContext();
    await db.Database.EnsureDeletedAsync();
    await db.Database.EnsureCreatedAsync();
    
    string[] values = ["abc", "def", "ghi"];
    
    await db.Blogs
        .RightJoin(values, blog => blog.AlternateKey, value => value,
            (blog, missingValue) => new { Blog = blog, MissingValue = missingValue })
        .Where(x => x.Blog == null)
        .Select(x => x.MissingValue)
        .ForEachAsync(Console.WriteLine);
    
    public class TestContext : DbContext
    {
        public DbSet<Blog> Blogs { get; set; }
    
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            => optionsBuilder
                .UseSqlServer(Environment.GetEnvironmentVariable("Test__SqlServer__DefaultConnection"))
                .LogTo(Console.WriteLine, LogLevel.Information)
                .EnableSensitiveDataLogging();
    
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Blog>().Property(x => x.AlternateKey).HasMaxLength(3);
        }
    }
    
    public class Blog
    {
        public int Id { get; set; }
        public required string AlternateKey { get; set; }
    }

    Exception:

    System.InvalidOperationException: Conflicting type mappings were inferred for column 'Value'.
       at Microsoft.EntityFrameworkCore.Query.RelationalTypeMappingPostprocessor.TryGetInferredTypeMapping(...)
       ...
    
  2. roji commented on Mar 18, 2026

    @roji
    Member

    @WhatzGames am closing this as a dup of dotnet/efcore#31776 - please check that removing the HasMaxLength() indeed makes the code run. Otherwise this doesn't seem to be specific to PG (reproducible with SQL Server) or to LeftJoin/RightJoin (reproducible with Join and other queries that involve two columns with differing/conflicting type mappings).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions