Skip to content

Collection type inference fails with conflicting mappings in some cases when a non-default mapping is used #31776

Open

Description

@ajcvickers
var foo = "12345";
var results = context.Set<Product>()
    .Where(c => new List<string?> { "ABCDE", foo }.Where(e => e != null)
        .Contains(c.Foo)).ToList();
Unhandled exception. System.InvalidOperationException: Conflicting type mappings were inferred for column 'value'.
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.RelationalInferredTypeMappingApplier.TryGetInferredTypeMapping(TableExpressionBase table, String columnName, RelationalTypeMapping& inferredTypeMapping)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.RelationalInferredTypeMappingApplier.VisitExtension(Expression expression)
   at Microsoft.EntityFrameworkCore.SqlServer.Query.Internal.SqlServerQueryableMethodTranslatingExpressionVisitor.SqlServerInferredTypeMappingApplier.VisitExtension(Expression expression)
   at Microsoft.EntityFrameworkCore.Query.SqlExpressions.ProjectionExpression.VisitChildren(ExpressionVisitor visitor)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.RelationalInferredTypeMappingApplier.VisitExtension(Expression expression)
   at Microsoft.EntityFrameworkCore.SqlServer.Query.Internal.SqlServerQueryableMethodTranslatingExpressionVisitor.SqlServerInferredTypeMappingApplier.VisitExtension(Expression expression)
   at Microsoft.EntityFrameworkCore.Query.SqlExpressions.SelectExpression.<VisitChildren>g__VisitList|124_0[T](List`1 list, Boolean inPlace, Boolean& changed, <>c__DisplayClass124_0&)
   at Microsoft.EntityFrameworkCore.Query.SqlExpressions.SelectExpression.VisitChildren(ExpressionVisitor visitor)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.RelationalInferredTypeMappingApplier.VisitExtension(Expression expression)
   at Microsoft.EntityFrameworkCore.SqlServer.Query.Internal.SqlServerQueryableMethodTranslatingExpressionVisitor.SqlServerInferredTypeMappingApplier.VisitExtension(Expression expression)
   at Microsoft.EntityFrameworkCore.Query.SqlExpressions.InExpression.VisitChildren(ExpressionVisitor visitor)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.RelationalInferredTypeMappingApplier.VisitExtension(Expression expression)
   at Microsoft.EntityFrameworkCore.SqlServer.Query.Internal.SqlServerQueryableMethodTranslatingExpressionVisitor.SqlServerInferredTypeMappingApplier.VisitExtension(Expression expression)
   at Microsoft.EntityFrameworkCore.Query.SqlExpressions.SelectExpression.VisitChildren(ExpressionVisitor visitor)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.RelationalInferredTypeMappingApplier.VisitExtension(Expression expression)
   at Microsoft.EntityFrameworkCore.SqlServer.Query.Internal.SqlServerQueryableMethodTranslatingExpressionVisitor.SqlServerInferredTypeMappingApplier.VisitExtension(Expression expression)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.RelationalInferredTypeMappingApplier.VisitExtension(Expression expression)
   at Microsoft.EntityFrameworkCore.SqlServer.Query.Internal.SqlServerQueryableMethodTranslatingExpressionVisitor.SqlServerInferredTypeMappingApplier.VisitExtension(Expression expression)
   at Microsoft.EntityFrameworkCore.SqlServer.Query.Internal.SqlServerQueryableMethodTranslatingExpressionVisitor.ApplyInferredTypeMappings(Expression expression, IReadOnlyDictionary`2 inferredTypeMappings)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.Translate(Expression expression)
   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__DisplayClass9_0`1.<Execute>b__0()
   at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQuery[TResult](Object cacheKey, Func`1 compiler)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.Execute[TResult](Expression query)
   at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.Execute[TResult](Expression expression)
   at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1.GetEnumerator()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at Program.<Main>$(String[] args) in C:\local\code\AllTogetherNow\Daily\Daily.cs:line 26
   at Program.<Main>(String[] args)
using (var context = new SomeDbContext())
{
    await context.Database.EnsureDeletedAsync();
    await context.Database.EnsureCreatedAsync();
}

using (var context = new SomeDbContext())
{
    var foo = "12345";
    var results = context.Set<Product>()
        .Where(c => new List<string?> { "ABCDE", foo }.Where(e => e != null)
            .Contains(c.Foo)).ToList();
}

public class SomeDbContext : DbContext
{
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        => optionsBuilder
            .UseSqlServer(@"Data Source=(LocalDb)\MSSQLLocalDB;Database=AllTogetherNow")
            .LogTo(Console.WriteLine, LogLevel.Information)
            .EnableSensitiveDataLogging();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Product>();
    }
}


public class Product
{
    public int Id { get; set; }

    [MaxLength(5)]
    public string? Foo { get; set; }
}

Activity

  1. ajcvickers commented on Sep 17, 2023

    @ajcvickers
    ContributorAuthor

    Note: not a regression from 7.0.

  2. added this to the 8.0.0 milestone on Sep 22, 2023
  3. changed the title [-]Contains on inline enumerable against column with facet throws[/-] [+]Collection type inference fails with conflicting mappings in some cases when a non-default mapping is used[/+] on Oct 8, 2023
  4. roji commented on Oct 8, 2023

    @roji
    Member

    Here's what's happening here:

    var results = context.Set<Product>()
        .Where(c => new List<string?> { "ABCDE", foo }.Where(e => e != null)
            .Contains(c.Foo)).ToList();

    This translates to:

    SELECT 1
    FROM Product AS p
    WHERE p.Foo IN (
        SELECT p0.value
        FROM OPENJSON(@__p_0) AS p0
        WHERE p0.value != NULL)
    • First, we infer p0.value from p.Foo (inference for InExpression with subquery), which is the correct thing to do. This picks up the non-default type mapping from p.Foo (nvarchar(5)).
    • However, when processing the WHERE clause of the subquery, p0.value there has the default mapping (nvarchar(max)); this is because when we create the binary expression (!= NULL), since there's no type mapping on either side, SqlExpressionFactory.ApplyTypeMappingOnSqlBinary simply looks up the default type mapping for the left side's CLR type.
    • At this point we have two conflicting type mappings, and translation fails.

    More generally, this is a result of primitive collections making type inference more complicated and deferred. We should think about how to improve this in 9.0, possibly by not assuming the default type mapping based on the CLR type.

  5. removed this from the 8.0.0 milestone on Oct 8, 2023
  6. added this to the Backlog milestone on Oct 11, 2023
  7. frankbuckley commented on Jan 1, 2024

    @frankbuckley

    I think I may be hitting this - more specifically, when I include this filter:

    image

    I get:

      Message: 
    System.InvalidOperationException : Conflicting type mappings were inferred for column 'value'.
    
      Stack Trace: 
    RelationalInferredTypeMappingApplier.TryGetInferredTypeMapping(TableExpressionBase table, String columnName, RelationalTypeMapping& inferredTypeMapping)
    RelationalInferredTypeMappingApplier.VisitExtension(Expression expression)
    SqlServerInferredTypeMappingApplier.VisitExtension(Expression expression)
    ProjectionExpression.VisitChildren(ExpressionVisitor visitor)
    RelationalInferredTypeMappingApplier.VisitExtension(Expression expression)
    SqlServerInferredTypeMappingApplier.VisitExtension(Expression expression)
    SelectExpression.<VisitChildren>g__VisitList|125_0[T](List`1 list, Boolean inPlace, Boolean& changed, <>c__DisplayClass125_0&)
    SelectExpression.VisitChildren(ExpressionVisitor visitor)
    RelationalInferredTypeMappingApplier.VisitExtension(Expression expression)
    SqlServerInferredTypeMappingApplier.VisitExtension(Expression expression)
    InExpression.VisitChildren(ExpressionVisitor visitor)
    RelationalInferredTypeMappingApplier.VisitExtension(Expression expression)
    SqlServerInferredTypeMappingApplier.VisitExtension(Expression expression)
    SqlBinaryExpression.VisitChildren(ExpressionVisitor visitor)
    RelationalInferredTypeMappingApplier.VisitExtension(Expression expression)
    SqlServerInferredTypeMappingApplier.VisitExtension(Expression expression)
    SelectExpression.VisitChildren(ExpressionVisitor visitor)
    RelationalInferredTypeMappingApplier.VisitExtension(Expression expression)
    SqlServerInferredTypeMappingApplier.VisitExtension(Expression expression)
    SelectExpression.<VisitChildren>g__VisitList|125_0[T](List`1 list, Boolean inPlace, Boolean& changed, <>c__DisplayClass125_0&)
    SelectExpression.VisitChildren(ExpressionVisitor visitor)
    RelationalInferredTypeMappingApplier.VisitExtension(Expression expression)
    SqlServerInferredTypeMappingApplier.VisitExtension(Expression expression)
    RelationalInferredTypeMappingApplier.VisitExtension(Expression expression)
    SqlServerInferredTypeMappingApplier.VisitExtension(Expression expression)
    SqlServerQueryableMethodTranslatingExpressionVisitor.ApplyInferredTypeMappings(Expression expression, IReadOnlyDictionary`2 inferredTypeMappings)
    RelationalQueryableMethodTranslatingExpressionVisitor.Translate(Expression expression)
    QueryCompilationContext.CreateQueryExecutor[TResult](Expression query)
    Database.CompileQuery[TResult](Expression query, Boolean async)
    QueryCompiler.CompileQueryCore[TResult](IDatabase database, Expression query, IModel model, Boolean async)
    <>c__DisplayClass12_0`1.<ExecuteAsync>b__0()
    CompiledQueryCache.GetOrAddQuery[TResult](Object cacheKey, Func`1 compiler)
    QueryCompiler.ExecuteAsync[TResult](Expression query, CancellationToken cancellationToken)
    EntityQueryProvider.ExecuteAsync[TResult](Expression expression, CancellationToken cancellationToken)
    EntityQueryable`1.GetAsyncEnumerator(CancellationToken cancellationToken)
    ConfiguredCancelableAsyncEnumerable`1.GetAsyncEnumerator()
    AsyncEnumerable.<ToListAsync>g__Core|424_0[TSource](IAsyncEnumerable`1 source, CancellationToken cancellationToken)
    FindWordsCommandHandlerTests.CanExecuteSearchingForWordIds() line 42
    

    If I remove the filter, there is no exception:

    image

    (Using EF 8.0 and .NET 8.0.0)

  8. mattpugsley commented on Mar 5, 2024

    @mattpugsley

    Is there a workaround, such as providing explicit ef typing/configuration to a non-model object like a string array? I like to use varchar because it's half the space of nvarchar, and I commonly compare strings with string arrays. I generally exclude nulls with != null before comparing with Contains to ensure that a null value in the sql record doesn't count as being contained by the array.

    I can provide an anonymized query if that would help, but I think it's the same issue that has already been identified.

    Error message:
    System.InvalidOperationException: Conflicting type mappings were inferred for column 'value'. at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.RelationalInferredTypeMappingApplier.TryGetInferredTypeMapping(TableExpressionBase table, String columnName, RelationalTypeMapping& inferredTypeMapping)

    I recently updated from .net 7 and EF 7 to .net 8 and EF8. I did not encounter the exception before, and if I keep .net 8 but revert to EF 7.0.16, the exception goes away.

  9. roji commented on Mar 5, 2024

    @roji
    Member

    @mattpugsley I'd have to think about it, but unfortunately I don't think there's a workaround... I intend to revisit this and hopefully fix it for 9.0 though.

  10. frankbuckley commented on Mar 5, 2024

    @frankbuckley

    Is there a workaround...

    We haven't found one for our examples (which seem to always be filters on ThenInclude() with a .Contains()).

  11. mattpugsley commented on Mar 25, 2024

    @mattpugsley

    I haven't tested with a filtered includes, but the following workaround is successful for me in a where clause:

    Instead of trying to make the array look like a varchar array, temporarily make the field look like an nvarchar field by using Convert.ToString(x). Per https://stackoverflow.com/questions/72758236/ef-core-function-to-pass-as-in-cast-value-as-varchar1024, this will tell sql to cast the value as nvarchar(max) (i.e. as part of the generated sql query). Although this might be an issue for projected data (i.e. I would prefer to not cast returned data), this is 'just' filtering, and so I don't have an issue using this cast.

    I continue to hope that EF 9 can be made to work with string array Contains against varchar fields (as in EF 7) without this workaround, but until/unless that is possible, I think that this workaround will work for me.

    var myArray = new[] { "A", "B" }; myContext.myDbSet.Where(x => myArray.Contains(Convert.ToString(x.MyVarcharField))).ToArray();

  12. roji commented on Mar 25, 2024

    @roji
    Member

    Thanks for that info @mattpugsley. This is definitely something we intend to improve for 9.

  13. ta1H3n commented on Feb 4, 2025

    @ta1H3n

    Just noting that this is still an issue in 9.

    The workaround to wrap the property in Convert.ToString that @mattpugsley suggested still works on my end

  14. added theissue type on Jun 15, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions