Skip to content

Union/Except over two array columns throws "Conflicting type mappings were inferred for column 'value'": NpgsqlTypeMappingPostprocessor infers the mapping of an unnest over a column #3940

Closed

Description

@AdCodicem

Description

When a query unnests an array column (a primitive collection), NpgsqlTypeMappingPostprocessor still infers the array's type mapping from the expressions that reference the element, and applies a rebuilt array mapping to the column (NpgsqlTypeMappingPostprocessor.cs, lines 44-55 on main at b09cc6c, the same file as in 10.0.3 and 11.0.0-rc.1.1):

case PgUnnestExpression unnestExpression
    when TryGetInferredTypeMapping(unnestExpression.Alias, unnestExpression.ColumnName, out var elementTypeMapping):
{
    var collectionTypeMapping = _typeMappingSource.FindMapping(unnestExpression.Array.Type, _model, elementTypeMapping);
    ...
    return unnestExpression.Update(_sqlExpressionFactory.ApplyTypeMapping(unnestExpression.Array, collectionTypeMapping));
}

A column already has its mapping from the model, so there is nothing to infer. EF Core's own postprocessors skip such sources. On dotnet/efcore main at 53fc2fc, the same in 11.0 RC1:

Two consequences follow.

1. Plain LINQ: a set operation over two array columns whose element mappings differ. With Tags a List<string> (text[]) and Labels a List<string> whose elements have HasMaxLength(10) (character varying(10)[]):

db.Orders.Where(o => o.Tags.Union(o.Labels).Contains("x")).ToQueryString();
db.Orders.Where(o => o.Tags.Except(o.Labels).Any()).ToQueryString();
// InvalidOperationException: Conflicting type mappings were inferred for column 'value'.

For a set operation, RelationalTypeMappingPostprocessor's scanner registers each leg's mapping on the other leg's element column, beside the column's own. It sees text and character varying(10) for one column and records a conflict. TryGetInferredTypeMapping throws that conflict when Npgsql asks for it. On EF Core 11.0 RC1 the same query translates on SQL Server and on SQLite. SQLite translates it on 10.0 too. EF Core 10.0's SQL Server provider throws the same message, because it called TryGetInferredTypeMapping in its when clause before looking at the source; main checks the source first. With the change proposed below, Npgsql translates both queries, and PostgreSQL 17 returns the expected rows.

This is not dotnet/efcore#31776, which is about an inline or parameter collection, whose mapping does need inferring (#3787 was closed as a duplicate of it). Here both sides are columns.

2. A member translator that returns the element column under another type. We met this first. An IMemberTranslatorPlugin, registered by an IDbContextOptionsExtension, translates x.Value, where x is a struct mapped through a value converter, to the column read as the underlying type: new ColumnExpression(column.Name, column.TableAlias, column.Column, typeof(string), stringMapping, column.IsNullable). That way LIKE and comparisons apply to the bare column and its index. It uses public API only. For a table column it works on all three providers. For an element of a primitive collection, Npgsql infers the element mapping (string) from that re-typed column, builds the List<Code> array mapping over it, and NpgsqlArrayTypeMapping fails to build its comparer:

TargetInvocationException → TargetInvocationException → ArgumentException: Expression of type 'System.Func`3[System.String,System.String,System.Boolean]' cannot be used for parameter of type 'System.Func`3[Code,Code,System.Boolean]' of method 'Boolean Compare(System.Collections.Generic.IEnumerable`1[Code], System.Collections.Generic.IEnumerable`1[Code], System.Func`3[Code,Code,System.Boolean])' (Parameter 'arg2')
   at Microsoft.EntityFrameworkCore.ChangeTracking.ListOfValueTypesComparer`2..ctor(ValueComparer elementComparer)
   ...
   at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.Mapping.NpgsqlArrayTypeMapping`3..ctor(RelationalTypeMapping elementTypeMapping)
   ...
   at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlTypeMappingSource.FindCollectionMapping(...)
   at Microsoft.EntityFrameworkCore.Storage.RelationalTypeMappingSource.FindMapping(Type type, IModel model, CoreTypeMapping elementMapping)
   at Npgsql.EntityFrameworkCore.PostgreSQL.Query.Internal.NpgsqlTypeMappingPostprocessor.VisitExtension(Expression expression)

SQL Server (OPENJSON ... WITH ([value] nvarchar(34) '$')) and SQLite (json_each) translate the same plugin's query and keep the element's mapping. I can see that a member translator changing a column's CLR type may be outside what you support. It is listed here because it fails on the same line, and the change below fixes both.

Proposed change

Infer only for an unnest whose array has no type mapping of its own (a parameter, or an inline array), as the SQL Server and SQLite postprocessors do:

case PgUnnestExpression unnestExpression
    when unnestExpression.Array.TypeMapping is null
        && TryGetInferredTypeMapping(unnestExpression.Alias, unnestExpression.ColumnName, out var elementTypeMapping):

I tried this in a copy of the postprocessor, swapped in through IQueryTranslationPostprocessorFactory, against PostgreSQL 17, on 10.0.3 and on 11.0.0-rc.1.1 (fix-check/ in the repro project; its output is at the end of this report):

  • the plugin's queries translate (WHERE EXISTS (SELECT 1 FROM unnest(o."Codes") AS c(value) WHERE c.value LIKE @prefix_startswith)) and return the right rows;
  • parameter arrays are still inferred (unnest(@prefixes), o."Code" = ANY (@codes), o."Tags" && @prefixes) and return the right rows;
  • Union and Except over Tags and Labels translate and return the expected rows.

One behaviour changes. A set operation between arrays whose element store types PostgreSQL cannot unite, such as int[] and a List<int> stored as text[] through a converter, is refused today at translation with the same "Conflicting type mappings" message. With the change it reaches the server: 42804: UNION types integer and character varying cannot be matched. EF Core 11's SQL Server provider also translates that query. I have not run your test suite against the change.

Workaround

For 1, give both collections the same element facets. For 2, translate an element to a CAST of it (sqlExpressionFactory.Convert(element, typeof(string), stringMapping)) rather than to the column re-typed. The element then keeps its own mapping, Npgsql infers nothing new, and the SQL is c.value::character varying(34) LIKE .... EF Core 11 leaves that no-op cast out of the SQL.

Repro

Repro project: https://github.com/AdCodicem/dotnet-upstream-repros/tree/main/npgsql-unnest-column-inferred-mapping (./repro.sh translates the queries with no server; REPRO_DOCKER=1 ./repro.sh also runs them, and the proposed change, on a PostgreSQL 17 container it starts and removes). ToQueryString() needs no server. Set REPRO_POSTGRES to a connection string to also run the queries against PostgreSQL.

<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.3" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="10.0.12" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.12" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="10.0.12" />
  </ItemGroup>
</Project>
Program.cs
// NpgsqlTypeMappingPostprocessor infers the type mapping of the array an unnest reads from the columns referencing its
// element, even when that array is a column, which already has its mapping from the model. Two ways to see it:
//   1. plain LINQ: a set operation over two array columns whose element mappings differ only by facets
//      (text[] and character varying(10)[]) fails with "Conflicting type mappings were inferred for column 'value'";
//   2. a member translator plugin that returns the element column typed as another CLR type (here: `.Value` of a
//      value-converted struct, read as the column) fails with an ArgumentException out of NpgsqlArrayTypeMapping.
// The same queries are translated on SQL Server and SQLite. Set REPRO_POSTGRES to a connection string to also run them
// on a server.
using System.Reflection;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Query;
using Microsoft.EntityFrameworkCore.Query.SqlExpressions;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Microsoft.Extensions.DependencyInjection;

var postgres = Environment.GetEnvironmentVariable("REPRO_POSTGRES");
var stack = args.Contains("--stack"); // print each failure on Npgsql in full

var prefix = "FR";
short least = 2;
var plain = new (string Name, Func<ShopContext, IQueryable<Order>> Query)[]
{
    ("o.Tags.Union(o.Labels).Contains(\"x\")", db => db.Orders.Where(o => o.Tags.Union(o.Labels).Contains("x"))),
    ("o.Tags.Except(o.Labels).Any()", db => db.Orders.Where(o => o.Tags.Except(o.Labels).Any())),
};
var withPlugin = new (string Name, Func<ShopContext, IQueryable<Order>> Query)[]
{
    ("o.Code.Value.StartsWith(prefix)", db => db.Orders.Where(o => o.Code.Value.StartsWith(prefix))),
    ("o.Codes.Any(c => c.Value.StartsWith(prefix))", db => db.Orders.Where(o => o.Codes.Any(c => c.Value.StartsWith(prefix)))),
    ("o.Quantities.Any(q => q.Value > least)", db => db.Orders.Where(o => o.Quantities.Any(q => q.Value > least))),
};

foreach (var (title, queries, plugin) in new[]
{
    ("1. Plain LINQ, no plugin", plain, (TranslationMode?)null),
    ("2. With the member translator plugin (the column re-typed)", withPlugin, TranslationMode.Column),
    ("3. With the plugin writing a CAST instead (workaround)", withPlugin, TranslationMode.Cast),
})
{
    Console.WriteLine($"######## {title}");
    foreach (var provider in new[] { "Npgsql", "SqlServer", "Sqlite" })
    {
        Console.WriteLine($"== {provider}");
        foreach (var (name, query) in queries)
        {
            using var db = new ShopContext(provider, plugin);
            Console.WriteLine($"   {name}");
            try
            {
                var sql = query(db).ToQueryString().Split('\n').Select(l => l.Trim());
                Console.WriteLine($"      ok: {string.Join(" ", sql.SkipWhile(l => !l.StartsWith("WHERE", StringComparison.Ordinal)))}");
            }
            catch (Exception e)
            {
                Console.WriteLine($"      {Describe(e)}");
                if (stack && provider == "Npgsql")
                {
                    Console.WriteLine(e);
                }
            }
        }
    }
}

if (postgres is not null)
{
    Console.WriteLine("######## The same on PostgreSQL, executed");
    using (var seed = new ShopContext("Npgsql", null, postgres))
    {
        seed.Database.EnsureDeleted();
        seed.Database.EnsureCreated();
        seed.Orders.Add(new Order { Code = new("FR76"), Codes = [new("FR76"), new("BE68")], Quantities = [new(1), new(3)], Tags = ["a", "x"], Labels = ["b"] });
        seed.Orders.Add(new Order { Code = new("BE68"), Codes = [new("BE68")], Quantities = [new(1)], Tags = ["a"], Labels = ["a"] });
        seed.SaveChanges();
    }

    foreach (var (queries, plugin) in new[] { (plain, (TranslationMode?)null), (withPlugin, TranslationMode.Column), (withPlugin, TranslationMode.Cast) })
    {
        foreach (var (name, query) in queries)
        {
            using var db = new ShopContext("Npgsql", plugin, postgres);
            try
            {
                Console.WriteLine($"   {name} [{plugin?.ToString() ?? "no plugin"}]: {query(db).Count()} row(s)");
            }
            catch (Exception e)
            {
                Console.WriteLine($"   {name} [{plugin?.ToString() ?? "no plugin"}]:\n      {Describe(e)}");
            }
        }
    }
}

static string Describe(Exception e)
{
    var text = $"!! {e.GetType().Name}: {e.Message.Split('\n')[0]}";
    for (var inner = e.InnerException; inner is not null; inner = inner.InnerException)
    {
        text += $"\n         inner {inner.GetType().Name}: {inner.Message.Split('\n')[0]}";
    }

    return text;
}

public readonly record struct Code(string Value);

public readonly record struct Quantity(short Value);

public sealed class CodeConverter() : ValueConverter<Code, string>(c => c.Value, v => new Code(v));

public sealed class QuantityConverter() : ValueConverter<Quantity, short>(q => q.Value, v => new Quantity(v));

public class Order
{
    public int Id { get; set; }
    public Code Code { get; set; }
    public List<Code> Codes { get; set; } = [];
    public List<Quantity> Quantities { get; set; } = [];
    public List<string> Tags { get; set; } = [];
    public List<string> Labels { get; set; } = [];
}

public enum TranslationMode { Column, Cast }

public class ShopContext(string provider, TranslationMode? plugin, string? postgres = null) : DbContext
{
    public DbSet<Order> Orders => Set<Order>();

    protected override void OnConfiguring(DbContextOptionsBuilder options)
    {
        _ = provider switch
        {
            "Npgsql" => options.UseNpgsql(postgres ?? "Host=unused"),
            "SqlServer" => options.UseSqlServer("Server=unused"),
            _ => options.UseSqlite("Data Source=unused.db"),
        };

        if (plugin is { } mode)
        {
            ((IDbContextOptionsBuilderInfrastructure)options).AddOrUpdateExtension(new ValueQueriesExtension(mode));
        }
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
        => modelBuilder.Entity<Order>(order =>
        {
            order.Property(o => o.Code).HasConversion<CodeConverter>().HasMaxLength(34);
            order.PrimitiveCollection(o => o.Codes).ElementType(e => e.HasConversion<CodeConverter>().HasMaxLength(34));
            order.PrimitiveCollection(o => o.Quantities).ElementType(e => e.HasConversion<QuantityConverter>());
            order.PrimitiveCollection(o => o.Labels).ElementType(e => e.HasMaxLength(10)); // character varying(10)[]
        });
}

/// <summary>Translates `x.Value`, where x is mapped through a value converter, to the column read as the underlying type.</summary>
public sealed class ValueTranslator(IRelationalTypeMappingSource typeMappingSource, ISqlExpressionFactory sql, TranslationMode mode)
    : IMemberTranslator
{
    public SqlExpression? Translate(
        SqlExpression? instance, MemberInfo member, Type returnType, IDiagnosticsLogger<DbLoggerCategory.Query> logger)
    {
        if (member.Name != "Value"
            || instance is not { TypeMapping: { Converter: not null } typeMapping }
            || typeMappingSource.FindMapping(returnType, typeMapping.StoreType) is not { } mapping)
        {
            return null;
        }

        return mode == TranslationMode.Column && instance is ColumnExpression column
            ? new ColumnExpression(column.Name, column.TableAlias, column.Column, returnType, mapping, column.IsNullable)
            : sql.Convert(instance, returnType, mapping);
    }
}

public sealed class ValueTranslatorPlugin(IRelationalTypeMappingSource typeMappingSource, ISqlExpressionFactory sql, IDbContextOptions options)
    : IMemberTranslatorPlugin
{
    public IEnumerable<IMemberTranslator> Translators { get; } =
        [new ValueTranslator(typeMappingSource, sql, options.FindExtension<ValueQueriesExtension>()!.Mode)];
}

/// <summary>Registers the plugin, as any extension adding query services does.</summary>
public sealed class ValueQueriesExtension(TranslationMode mode) : IDbContextOptionsExtension
{
    public TranslationMode Mode { get; } = mode;

    public DbContextOptionsExtensionInfo Info => new ExtensionInfo(this);

    public void ApplyServices(IServiceCollection services)
        => new EntityFrameworkRelationalServicesBuilder(services).TryAdd<IMemberTranslatorPlugin, ValueTranslatorPlugin>();

    public void Validate(IDbContextOptions options)
    {
    }

    private sealed class ExtensionInfo(ValueQueriesExtension extension) : DbContextOptionsExtensionInfo(extension)
    {
        public override bool IsDatabaseProvider => false;

        public override string LogFragment => $"ValueQueries:{extension.Mode} ";

        public override int GetServiceProviderHashCode() => extension.Mode.GetHashCode();

        public override bool ShouldUseSameServiceProvider(DbContextOptionsExtensionInfo other)
            => other is ExtensionInfo info && ((ValueQueriesExtension)info.Extension).Mode == extension.Mode;

        public override void PopulateDebugInfo(IDictionary<string, string> debugInfo)
            => debugInfo["ValueQueries"] = extension.Mode.ToString();
    }
}

Output

On Npgsql 11.0.0-rc.1.1 / EF Core 11.0.0-rc.1.26425.128, part 1:

######## 1. Plain LINQ, no plugin
== Npgsql
   o.Tags.Union(o.Labels).Contains("x")
      !! InvalidOperationException: Conflicting type mappings were inferred for column 'value'.
   o.Tags.Except(o.Labels).Any()
      !! InvalidOperationException: Conflicting type mappings were inferred for column 'value'.
== SqlServer
   o.Tags.Union(o.Labels).Contains("x")
      ok: WHERE N'x' IN ( SELECT [t].[value] FROM OPENJSON([o].[Tags]) WITH ([value] nvarchar(max) '$') AS [t] UNION SELECT [l].[value] FROM OPENJSON([o].[Labels]) WITH ([value] nvarchar(10) '$') AS [l] )
   o.Tags.Except(o.Labels).Any()
      ok: WHERE EXISTS ( SELECT 1 FROM ( SELECT [t].[value] FROM OPENJSON([o].[Tags]) WITH ([value] nvarchar(max) '$') AS [t] EXCEPT SELECT [l].[value] FROM OPENJSON([o].[Labels]) WITH ([value] nvarchar(10) '$') AS [l] ) AS [e])
== Sqlite
   o.Tags.Union(o.Labels).Contains("x")
      ok: WHERE 'x' IN ( SELECT "t"."value" FROM json_each("o"."Tags") AS "t" UNION SELECT "l"."value" FROM json_each("o"."Labels") AS "l" )
   o.Tags.Except(o.Labels).Any()
      ok: WHERE EXISTS ( SELECT 1 FROM ( SELECT "t"."value" FROM json_each("o"."Tags") AS "t" EXCEPT SELECT "l"."value" FROM json_each("o"."Labels") AS "l" ) AS "e")

On Npgsql 10.0.3 / EF Core 10.0.12, part 1 is the same on Npgsql, but SQL Server 10.0.12 throws too:

######## 1. Plain LINQ, no plugin
== Npgsql
   o.Tags.Union(o.Labels).Contains("x")
      !! InvalidOperationException: Conflicting type mappings were inferred for column 'value'.
   o.Tags.Except(o.Labels).Any()
      !! InvalidOperationException: Conflicting type mappings were inferred for column 'value'.
== SqlServer
   o.Tags.Union(o.Labels).Contains("x")
      !! InvalidOperationException: Conflicting type mappings were inferred for column 'value'.
   o.Tags.Except(o.Labels).Any()
      !! InvalidOperationException: Conflicting type mappings were inferred for column 'value'.
== Sqlite
   o.Tags.Union(o.Labels).Contains("x")
      ok: WHERE 'x' IN ( SELECT "t"."value" FROM json_each("o"."Tags") AS "t" UNION SELECT "l"."value" FROM json_each("o"."Labels") AS "l" )
   o.Tags.Except(o.Labels).Any()
      ok: WHERE EXISTS ( SELECT 1 FROM ( SELECT "t"."value" FROM json_each("o"."Tags") AS "t" EXCEPT SELECT "l"."value" FROM json_each("o"."Labels") AS "l" ) AS "e")

Part 2, the plugin (10.0.3; the same on 11.0.0-rc.1.1):

######## 2. With the member translator plugin (the column re-typed)
== Npgsql
   o.Code.Value.StartsWith(prefix)
      ok: WHERE o."Code" LIKE @prefix_startswith
   o.Codes.Any(c => c.Value.StartsWith(prefix))
      !! TargetInvocationException: Exception has been thrown by the target of an invocation.
         inner TargetInvocationException: Exception has been thrown by the target of an invocation.
         inner ArgumentException: Expression of type 'System.Func`3[System.String,System.String,System.Boolean]' cannot be used for parameter of type 'System.Func`3[Code,Code,System.Boolean]' of method 'Boolean Compare(System.Collections.Generic.IEnumerable`1[Code], System.Collections.Generic.IEnumerable`1[Code], System.Func`3[Code,Code,System.Boolean])' (Parameter 'arg2')
   o.Quantities.Any(q => q.Value > least)
      !! TargetInvocationException: Exception has been thrown by the target of an invocation.
         inner TargetInvocationException: Exception has been thrown by the target of an invocation.
         inner ArgumentException: Expression of type 'System.Func`3[System.Int16,System.Int16,System.Boolean]' cannot be used for parameter of type 'System.Func`3[Quantity,Quantity,System.Boolean]' of method 'Boolean Compare(System.Collections.Generic.IEnumerable`1[Quantity], System.Collections.Generic.IEnumerable`1[Quantity], System.Func`3[Quantity,Quantity,System.Boolean])' (Parameter 'arg2')
== SqlServer
   o.Code.Value.StartsWith(prefix)
      ok: WHERE [o].[Code] LIKE @prefix_startswith ESCAPE N'\'
   o.Codes.Any(c => c.Value.StartsWith(prefix))
      ok: WHERE EXISTS ( SELECT 1 FROM OPENJSON([o].[Codes]) WITH ([value] nvarchar(34) '$') AS [c] WHERE [c].[value] LIKE @prefix_startswith ESCAPE N'\')
   o.Quantities.Any(q => q.Value > least)
      ok: WHERE EXISTS ( SELECT 1 FROM OPENJSON([o].[Quantities]) WITH ([value] smallint '$') AS [q] WHERE [q].[value] > @least)
== Sqlite
   o.Code.Value.StartsWith(prefix)
      ok: WHERE "o"."Code" LIKE @prefix_startswith ESCAPE '\'
   o.Codes.Any(c => c.Value.StartsWith(prefix))
      ok: WHERE EXISTS ( SELECT 1 FROM json_each("o"."Codes") AS "c" WHERE "c"."value" LIKE @prefix_startswith ESCAPE '\')
   o.Quantities.Any(q => q.Value > least)
      ok: WHERE EXISTS ( SELECT 1 FROM json_each("o"."Quantities") AS "q" WHERE "q"."value" > @least)

Executed on PostgreSQL 17.11 (10.0.3; the same on 11.0.0-rc.1.1):

######## The same on PostgreSQL, executed
   o.Tags.Union(o.Labels).Contains("x") [no plugin]:
      !! InvalidOperationException: Conflicting type mappings were inferred for column 'value'.
   o.Tags.Except(o.Labels).Any() [no plugin]:
      !! InvalidOperationException: Conflicting type mappings were inferred for column 'value'.
   o.Code.Value.StartsWith(prefix) [Column]: 1 row(s)
   o.Codes.Any(c => c.Value.StartsWith(prefix)) [Column]:
      !! TargetInvocationException: Exception has been thrown by the target of an invocation.
         inner TargetInvocationException: Exception has been thrown by the target of an invocation.
         inner ArgumentException: Expression of type 'System.Func`3[System.String,System.String,System.Boolean]' cannot be used for parameter of type 'System.Func`3[Code,Code,System.Boolean]' of method 'Boolean Compare(System.Collections.Generic.IEnumerable`1[Code], System.Collections.Generic.IEnumerable`1[Code], System.Func`3[Code,Code,System.Boolean])' (Parameter 'arg2')
   o.Quantities.Any(q => q.Value > least) [Column]:
      !! TargetInvocationException: Exception has been thrown by the target of an invocation.
         inner TargetInvocationException: Exception has been thrown by the target of an invocation.
         inner ArgumentException: Expression of type 'System.Func`3[System.Int16,System.Int16,System.Boolean]' cannot be used for parameter of type 'System.Func`3[Quantity,Quantity,System.Boolean]' of method 'Boolean Compare(System.Collections.Generic.IEnumerable`1[Quantity], System.Collections.Generic.IEnumerable`1[Quantity], System.Func`3[Quantity,Quantity,System.Boolean])' (Parameter 'arg2')
   o.Code.Value.StartsWith(prefix) [Cast]: 1 row(s)
   o.Codes.Any(c => c.Value.StartsWith(prefix)) [Cast]: 1 row(s)
   o.Quantities.Any(q => q.Value > least) [Cast]: 1 row(s)
As shipped and with the proposed change, on PostgreSQL 17.11 (10.0.3; the same on 11.0.0-rc.1.1)
== o.Tags.Union(o.Labels).Contains("x")   (expected: 1 row)
   as shipped:               !! InvalidOperationException: Conflicting type mappings were inferred for column 'value'.
   with the proposed change: 1 row(s)
      WHERE 'x' IN ( SELECT t.value FROM unnest(o."Tags") AS t(value) UNION SELECT l.value FROM unnest(o."Labels") AS l(value) )
== o.Tags.Except(o.Labels).Any()   (expected: 1 row)
   as shipped:               !! InvalidOperationException: Conflicting type mappings were inferred for column 'value'.
   with the proposed change: 1 row(s)
      WHERE EXISTS ( SELECT 1 FROM ( SELECT t.value FROM unnest(o."Tags") AS t(value) EXCEPT SELECT l.value FROM unnest(o."Labels") AS l(value) ) AS e)
== o.Tags.Select(t => t + "!").Union(o.Labels.Select(l => l + "!")).Contains("x!")   (expected: 1 row)
   as shipped:               1 row(s)
      WHERE 'x!' IN ( SELECT t.value || '!' AS c FROM unnest(o."Tags") AS t(value) UNION SELECT l.value || '!' AS c FROM unnest(o."Labels") AS l(value) )
   with the proposed change: 1 row(s)
      WHERE 'x!' IN ( SELECT t.value || '!' AS c FROM unnest(o."Tags") AS t(value) UNION SELECT l.value || '!' AS c FROM unnest(o."Labels") AS l(value) )
== o.Codes.Any(c => c.Value.StartsWith(prefix))   (expected: 1 row)
   as shipped:               !! ArgumentException: Expression of type 'System.Func`3[System.String,System.String,System.Boolean]' cannot be used for parameter of type 'System.Func`3[Code,Code,System.Boolean]' of method 'Boolean Compare(System.Collections.Generic.IEnumerable`1[Code], System.Collections.Generic.IEnumerable`1[Code], System.Func`3[Code,Code,System.Boolean])' (Parameter 'arg2')
   with the proposed change: 1 row(s)
      WHERE EXISTS ( SELECT 1 FROM unnest(o."Codes") AS c(value) WHERE c.value LIKE @prefix_startswith)
== o.Quantities.Any(q => q.Value > least)   (expected: 1 row)
   as shipped:               !! ArgumentException: Expression of type 'System.Func`3[System.Int16,System.Int16,System.Boolean]' cannot be used for parameter of type 'System.Func`3[Quantity,Quantity,System.Boolean]' of method 'Boolean Compare(System.Collections.Generic.IEnumerable`1[Quantity], System.Collections.Generic.IEnumerable`1[Quantity], System.Func`3[Quantity,Quantity,System.Boolean])' (Parameter 'arg2')
   with the proposed change: 1 row(s)
      WHERE EXISTS ( SELECT 1 FROM unnest(o."Quantities") AS q(value) WHERE q.value > @least)
== prefixes.Any(p => o.Code.Value.StartsWith(p)), a string[] parameter   (expected: 1 row)
   as shipped:               1 row(s)
      WHERE EXISTS ( SELECT 1 FROM unnest(@prefixes) AS p(value) WHERE p.value IS NOT NULL AND left(o."Code", length(p.value))::character varying(34) = p.value)
   with the proposed change: 1 row(s)
      WHERE EXISTS ( SELECT 1 FROM unnest(@prefixes) AS p(value) WHERE p.value IS NOT NULL AND left(o."Code", length(p.value))::character varying(34) = p.value)
== codes.Contains(o.Code.Value), a string[] parameter   (expected: 1 row)
   as shipped:               1 row(s)
      WHERE o."Code" = ANY (@codes)
   with the proposed change: 1 row(s)
      WHERE o."Code" = ANY (@codes)
== o.Tags.Intersect(prefixes).Any(), a column and a string[] parameter   (expected: 0 rows)
   as shipped:               0 row(s)
      WHERE o."Tags" && @prefixes
   with the proposed change: 0 row(s)
      WHERE o."Tags" && @prefixes
== o.Numbers.Union(o.TextNumbers).Contains(1), integer[] and text[]   (expected: refused)
   as shipped:               !! InvalidOperationException: Conflicting type mappings were inferred for column 'value'.
   with the proposed change: !! PostgresException: 42804: UNION types integer and character varying cannot be matched
Stack trace of part 1 (10.0.3)
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.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.SqlExpressions.UnionExpression.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.SqlExpressions.InExpression.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(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.Execute[TResult](Expression query)
   at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.Execute[TResult](Expression expression)
   at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToQueryString(IQueryable source)
   at Program.<Main>$(String[] args) in <repro>/Program.cs:line 53
Stack trace of part 2 (10.0.3)
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.
 ---> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.
 ---> System.ArgumentException: Expression of type 'System.Func`3[System.String,System.String,System.Boolean]' cannot be used for parameter of type 'System.Func`3[Code,Code,System.Boolean]' of method 'Boolean Compare(System.Collections.Generic.IEnumerable`1[Code], System.Collections.Generic.IEnumerable`1[Code], System.Func`3[Code,Code,System.Boolean])' (Parameter 'arg2')
   at System.Dynamic.Utils.ExpressionUtils.ValidateOneArgument(MethodBase method, ExpressionType nodeKind, Expression arguments, ParameterInfo pi, String methodParamName, String argumentParamName, Int32 index)
   at System.Linq.Expressions.Expression.Call(MethodInfo method, Expression arg0, Expression arg1, Expression arg2)
   at Microsoft.EntityFrameworkCore.ChangeTracking.ListOfValueTypesComparer`2.CompareLambda(ValueComparer elementComparer)
   at Microsoft.EntityFrameworkCore.ChangeTracking.ListOfValueTypesComparer`2..ctor(ValueComparer elementComparer)
   at InvokeStub_ListOfValueTypesComparer`2..ctor(Object, Span`1)
   at System.Reflection.MethodBaseInvoker.InvokeWithOneArg(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   --- End of inner exception stack trace ---
   at System.Reflection.MethodBaseInvoker.InvokeWithOneArg(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture)
   at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.Mapping.NpgsqlArrayTypeMapping`3.CreateParameters(String storeType, RelationalTypeMapping elementMapping)
   at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.Mapping.NpgsqlArrayTypeMapping`3..ctor(String storeType, RelationalTypeMapping elementTypeMapping)
   at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.Mapping.NpgsqlArrayTypeMapping`3..ctor(RelationalTypeMapping elementTypeMapping)
   at InvokeStub_NpgsqlArrayTypeMapping`3..ctor(Object, Span`1)
   at System.Reflection.MethodBaseInvoker.InvokeWithOneArg(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   --- End of inner exception stack trace ---
   at System.Reflection.MethodBaseInvoker.InvokeWithOneArg(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture)
   at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlTypeMappingSource.FindCollectionMapping(String storeType, Type modelClrType, Type providerClrType, CoreTypeMapping elementMapping)
   at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlTypeMappingSource.FindCollectionMapping(RelationalTypeMappingInfo info, Type modelType, Type providerType, CoreTypeMapping elementMapping)
   at Microsoft.EntityFrameworkCore.Storage.RelationalTypeMappingSource.<>c.<FindMappingWithConversion>b__8_0(ValueTuple`4 k, RelationalTypeMappingSource self)
   at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd[TArg](TKey key, Func`3 valueFactory, TArg factoryArgument)
   at Microsoft.EntityFrameworkCore.Storage.RelationalTypeMappingSource.FindMappingWithConversion(RelationalTypeMappingInfo mappingInfo, Type providerClrType, ValueConverter customConverter)
   at Microsoft.EntityFrameworkCore.Storage.RelationalTypeMappingSource.FindMapping(Type type, IModel model, CoreTypeMapping elementMapping)
   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.SqlExpressions.ExistsExpression.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(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.Execute[TResult](Expression query)
   at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.Execute[TResult](Expression expression)
   at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToQueryString(IQueryable source)
   at Program.<Main>$(String[] args) in <repro>/Program.cs:line 53

Versions

  • Npgsql.EntityFrameworkCore.PostgreSQL 10.0.3 with EF Core 10.0.12 (also 11.0.0-rc.1.1 with EF Core 11.0.0-rc.1.26425.128)
  • PostgreSQL 17.11
  • .NET 10.0 (SDK 10.0.401); also .NET 11.0 RC1 (SDK 11.0.100-rc.1.26425.128)
  • Windows 11 (10.0.26200) x64 and Ubuntu 24.04 x64

Found while translating .Value in queries for AdCodicem.ValueObjects. Investigation and write-up assisted by Claude (Anthropic); the linked repro was run on Windows 11 and Ubuntu 24.04, against PostgreSQL 17.11, and I reviewed this report.

Activity

  1. added theissue type on Oct 14, 2026
  2. roji commented on Oct 14, 2026

    @roji
    Member

    AI Triage

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

    Confirmed: this is a provider-side bug, and it can be fixed in Npgsql without changing EF Core.

    The minimal case needs only two mapped string collections with different element facets. EF's type-mapping scanner records conflicting inferred mappings for the set-operation legs, but those collections already have mappings from the model. NpgsqlTypeMappingPostprocessor unnecessarily calls TryGetInferredTypeMapping on their unnest expressions, which throws before the existing mappings can be retained.

    I reproduced both Union(...).Contains(...) and Except(...).Any() with:

    Provider / version Result
    Npgsql 8.0.0 / EF 8.0.0 Both fail
    Npgsql 9.0.0 / EF 9.0.0 Both fail
    Npgsql 10.0.3 / EF 10.0.12 Both fail
    Npgsql 11.0.0-rc.1.1 / EF 11.0.0-rc.1.26425.128 Both fail
    SQL Server / EF 10.0.12 Both fail
    SQL Server / EF 11.0.0-rc.1.26425.128 Both translate
    SQLite / EF 10.0.12 and 11.0.0-rc.1.26425.128 Both translate

    This is not a recent regression: it already occurs in 8.0.0, the release that introduced EF's primitive-collection querying.

    The local fix restricts inference to PgUnnestExpression { Array.TypeMapping: null }. This preserves mappings already supplied by the model while still allowing inference for untyped collection expressions. I added a regression test checking the returned rows and exact SQL for both operations. The affected array, primitive-collection, and ad-hoc query test classes passed: 440 passed, 3 existing skips.

    I also ran the original linked repro against the fixed provider on PostgreSQL 18.4: both set operations and the member translator's string/quantity collection queries translated and returned the expected rows. As noted in the report, incompatible mapped store types are then rejected by PostgreSQL rather than by the unnecessary inference step.

    Related issues dotnet/efcore#31776 and dotnet/efcore#31109 concern inference for collections that actually need a mapping; they do not require deferring this fix for already-mapped columns. SQL Server's corresponding ordering change is present in dotnet/efcore#37372.

    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.3" />
        <PackageReference Include="Microsoft.EntityFrameworkCore" Version="10.0.12" />
      </ItemGroup>
    </Project>

    Program.cs:

    using Microsoft.EntityFrameworkCore;
    using Microsoft.Extensions.Logging;
    
    using var db = new ShopContext();
    Console.WriteLine(db.Orders.Where(o => o.Tags.Union(o.Labels).Contains("x")).ToQueryString());
    
    public class ShopContext : DbContext
    {
        public DbSet<Order> Orders => Set<Order>();
    
        protected override void OnConfiguring(DbContextOptionsBuilder options)
            => options
                .UseNpgsql("Host=localhost")
                .LogTo(Console.WriteLine, LogLevel.Information)
                .EnableSensitiveDataLogging();
    
        protected override void OnModelCreating(ModelBuilder modelBuilder)
            => modelBuilder.Entity<Order>().PrimitiveCollection(o => o.Labels).ElementType().HasMaxLength(10);
    }
    
    public class Order
    {
        public int Id { get; set; }
        public List<string> Tags { get; set; } = [];
        public List<string> Labels { get; set; } = [];
    }

    No database is required to reproduce the translation exception. Replacing the query with db.Orders.Where(o => o.Tags.Except(o.Labels).Any()).ToQueryString() reproduces the other failure.

  3. self-assigned this
    on Oct 14, 2026
  4. added this to the 10.0.4 milestone on Oct 14, 2026
  5. added a commit that references this issue on Oct 16, 2026
    e470300
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