Skip to content

No coercion operator is defined between nullable and not nullable type after upgrade from EFCore8 to EFCore9 #35117

Closed

Description

@dario-l

We have are extensively use typed identifiers.

For Example:

public readonly record struct AreaLocationId(int Value);

Which can be mapped as not required nullable foreign key like this:

builder.Property(e => e.LocationId)
    .HasConversion(
        id => id == null ? (int?)null : id.Value.Value,
        value => value == null ? null : new AreaLocationId(value.Value));

and in where linq clause I can write like this:

...
var result = await db
    ...
    .Where(x => x.LocationId != null && availableLocations.Contains(x.LocationId.Value))
    .ToListAsync(ct);

With EF Core8 everything works fine. After switching to EFCore9 in the line above we have exception:

Unhandled exception: "Exception has been thrown by the target of an invocation."
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. --->
System.InvalidOperationException: No coercion operator is defined between types 'Microsoft.EntityFrameworkCore.ChangeTracking.ValueComparer1[System.Nullable1[TimeHarmony.Shared.Areas.AreaLocationId]]' and 'Microsoft.EntityFrameworkCore.ChangeTracking.ValueComparer1[TimeHarmony.Shared.Areas.AreaLocationId]

Only downgrading to EF Core 8.0.11 solves the issue.

EF Core version: 9.0.0
Database provider: Microsoft.EntityFrameworkCore.SqlServer
Target framework: .NET 9.0

Activity

  1. ajcvickers commented on Nov 15, 2024

    @ajcvickers
    Contributor

    Confirmed regression from EF8. Full repro below.

    Unhandled exception. System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.
     ---> System.InvalidOperationException: No coercion operator is defined between types 'Microsoft.EntityFrameworkCore.ChangeTracking.ValueComparer`1[System.Nullable`1[AreaLocationId]]' and 'Microsoft.EntityFrameworkCore.ChangeTracking.ValueComparer`1[AreaLocationId]'.
       at System.Linq.Expressions.Expression.GetUserDefinedCoercionOrThrow(ExpressionType coercionType, Expression expression, Type convertToType)
       at Microsoft.EntityFrameworkCore.ChangeTracking.ListOfValueTypesComparer`2.CompareLambda(ValueComparer elementComparer)
       at Microsoft.EntityFrameworkCore.ChangeTracking.ListOfValueTypesComparer`2..ctor(ValueComparer elementComparer)
       at System.RuntimeMethodHandle.InvokeMethod(Object target, Void** arguments, Signature sig, Boolean isConstructor)
       at System.Reflection.MethodBaseInvoker.InvokeDirectByRefWithFewArgs(Object obj, Span`1 copyOfArgs, BindingFlags invokeAttr)
       --- End of inner exception stack trace ---
       at System.Reflection.MethodBaseInvoker.InvokeDirectByRefWithFewArgs(Object obj, Span`1 copyOfArgs, BindingFlags invokeAttr)
       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 System.Activator.CreateInstance(Type type, Object[] args)
       at Microsoft.EntityFrameworkCore.Storage.TypeMappingSourceBase.TryFindJsonCollectionMapping(TypeMappingInfo mappingInfo, Type modelClrType, Type providerClrType, CoreTypeMapping& elementMapping, ValueComparer& elementComparer, JsonValueReaderWriter& collectionReaderWriter)
       at Microsoft.EntityFrameworkCore.Storage.RelationalTypeMappingSource.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 Microsoft.EntityFrameworkCore.SqlServer.Query.Internal.SqlServerTypeMappingPostprocessor.ApplyTypeMappingsOnOpenJsonExpression(SqlServerOpenJsonExpression openJsonExpression, IReadOnlyList`1 typeMappings)
       at Microsoft.EntityFrameworkCore.SqlServer.Query.Internal.SqlServerTypeMappingPostprocessor.VisitExtension(Expression expression)
       at Microsoft.EntityFrameworkCore.Query.SqlExpressions.SelectExpression.<VisitChildren>g__VisitList|117_0[T](List`1 list, Boolean inPlace, Boolean& changed, <>c__DisplayClass117_0&)
       at Microsoft.EntityFrameworkCore.Query.SqlExpressions.SelectExpression.VisitChildren(ExpressionVisitor visitor)
       at Microsoft.EntityFrameworkCore.Query.RelationalTypeMappingPostprocessor.VisitExtension(Expression expression)
       at Microsoft.EntityFrameworkCore.SqlServer.Query.Internal.SqlServerTypeMappingPostprocessor.VisitExtension(Expression expression)
       at Microsoft.EntityFrameworkCore.Query.SqlExpressions.InExpression.VisitChildren(ExpressionVisitor visitor)
       at Microsoft.EntityFrameworkCore.Query.RelationalTypeMappingPostprocessor.VisitExtension(Expression expression)
       at Microsoft.EntityFrameworkCore.SqlServer.Query.Internal.SqlServerTypeMappingPostprocessor.VisitExtension(Expression expression)
       at Microsoft.EntityFrameworkCore.Query.SqlExpressions.SqlBinaryExpression.VisitChildren(ExpressionVisitor visitor)
       at Microsoft.EntityFrameworkCore.Query.RelationalTypeMappingPostprocessor.VisitExtension(Expression expression)
       at Microsoft.EntityFrameworkCore.SqlServer.Query.Internal.SqlServerTypeMappingPostprocessor.VisitExtension(Expression expression)
       at Microsoft.EntityFrameworkCore.Query.SqlExpressions.SelectExpression.VisitChildren(ExpressionVisitor visitor)
       at Microsoft.EntityFrameworkCore.Query.RelationalTypeMappingPostprocessor.VisitExtension(Expression expression)
       at Microsoft.EntityFrameworkCore.SqlServer.Query.Internal.SqlServerTypeMappingPostprocessor.VisitExtension(Expression expression)
       at Microsoft.EntityFrameworkCore.Query.RelationalTypeMappingPostprocessor.VisitExtension(Expression expression)
       at Microsoft.EntityFrameworkCore.SqlServer.Query.Internal.SqlServerTypeMappingPostprocessor.VisitExtension(Expression expression)
       at Microsoft.EntityFrameworkCore.Query.RelationalTypeMappingPostprocessor.Process(Expression expression)
       at Microsoft.EntityFrameworkCore.SqlServer.Query.Internal.SqlServerQueryTranslationPostprocessor.ProcessTypeMappings(Expression expression)
       at Microsoft.EntityFrameworkCore.Query.RelationalQueryTranslationPostprocessor.Process(Expression query)
       at Microsoft.EntityFrameworkCore.SqlServer.Query.Internal.SqlServerQueryTranslationPostprocessor.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.ToListAsync[TSource](IQueryable`1 source, CancellationToken cancellationToken)
       at Program.<Main>$(String[] args) in D:\code\DoomSlug\DoomSlug\Program.cs:line 42
       at Program.<Main>(String[] args)
    
    Full repro
    using (var context = new ContextOfDoom())
    {
        await context.Database.EnsureDeletedAsync();
        await context.Database.EnsureCreatedAsync();
    }
    
    using (var context = new ContextOfDoom())
    {
        var availableLocations = new List<AreaLocationId> { new(1), new(2) };
        
        var result = await context.Set<Product>()
            .Where(x => x.LocationId != null && availableLocations.Contains(x.LocationId.Value))
            .ToListAsync();
    }
    
    public class ContextOfDoom : DbContext
    {
        public DbSet<Product> Products => Set<Product>();
    
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            => optionsBuilder
                .EnableSensitiveDataLogging()
                .LogTo(Console.WriteLine)
                .UseSqlServer(
                    "Server=localhost;Database=DoomSlug;Trusted_Connection=True;TrustServerCertificate=True");
    
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Product>(b =>
            {
                b.Property(e => e.LocationId)
                    .HasConversion(
                        id => id == null ? (int?)null : id.Value.Value,
                        value => value == null ? null : new AreaLocationId(value.Value));
                b.HasKey(e => e.LocationId);
            });
        }
    }
    
    public class Product
    {
        public AreaLocationId? LocationId { get; set; }
    }
    
    public readonly record struct AreaLocationId(int Value);
  2. self-assigned this
    on Nov 15, 2024
  3. added this to the 10.0.0 milestone on Nov 15, 2024
  4. dario-l commented on Nov 15, 2024

    @dario-l
    Author

    Wow... serious issue as I can see. 😞

    Image

  5. roji commented on Nov 15, 2024

    @roji
    Member

    @dario-l that doesn't mean we won't backport the fix to 9.0 (e.g. for 9.0.1). What we end up doing depends on the complexity/risk of the fix, etc.

  6. dario-l commented on Nov 15, 2024

    @dario-l
    Author

    @roji Thanks for explanation. That's a relief. 👍🏻

  7. rabberbock commented on Nov 25, 2024

    @rabberbock

    I also ran into a similar issue.

     int? number = 10;
     var t = await _applicationContext.Projects
        .Select(p => new
        {
            IntValue = Math.Min(p.MaxTimes, number ?? 10)
        })
        .FirstAsync(); 
    

    Because number is nullable this no longer works in EF Core 9 with the following error,

    Expression of type 'System.Nullable`1[System.Int32]' cannot be used for parameter of type 'System.Int32' 
    

    Let me know if you think I should open a separate issue. Thanks!

  8. roji commented on Nov 25, 2024

    @roji
    Member

    @rabberbock if you could post a minimal, runnable console program for your case that would be ideal, this way we can check it as we fix this.

  9. rabberbock commented on Nov 25, 2024

    @rabberbock
  10. ajcvickers commented on Nov 27, 2024

    @ajcvickers
    Contributor

    @dario-l A workaround here is to use a parameter type that matches the property type. So in this case a nullable int rather than a normal int:

    var availableLocations = new List<AreaLocationId?> { new(1), new(2) };

    Note for team: the root cause here is that we get a List<AreaLocationId> as the parameter type, which cannot be used with the property type which is AreaLocationId?. We either need better inference, or more forgiving collections.

  11. ajcvickers commented on Nov 27, 2024

    @ajcvickers
    Contributor

    @rabberbock I moved your issue to #35227 since it is not the same as the issue reported here.

  12. 3 remaining items

  13. ajcvickers commented on Nov 28, 2024

    @ajcvickers
    Contributor

    Note for team: the root cause of the mismatch is the value comparer defined for a nullable value type. This is not recommended (we may want better docs) unless the converter must handle nulls, which is rare. We may want to wait for more feedback before backporting.

    @dario-l I recommend you change your value converter to work with the non-nullable value type. For example:

    protected class AreaLocationIdConverter() : ValueConverter<AreaLocationId, int>(v => v.Value, v => new(v));

    And then used like this:

    b.Property(e => e.LocationId).HasConversion<AreaLocationIdConverter>();
  14. ajcvickers commented on Nov 30, 2024

    @ajcvickers
    Contributor

    Re-open to consider patching.

  15. ossendorf-at-hoelscher commented on Dec 2, 2024

    @ossendorf-at-hoelscher

    We are experiencing the same exception but not with a collection.

    Message: No coercion operator is defined between types 'Microsoft.EntityFrameworkCore.ChangeTracking.ValueComparer`1[System.Nullable`1[System.Int32]]' and 'Microsoft.EntityFrameworkCore.ChangeTracking.ValueComparer`1[System.Int32]'.
    
    Stacktrace:
       at System.Linq.Expressions.Expression.GetUserDefinedCoercionOrThrow(ExpressionType coercionType, Expression expression, Type convertToType)
       at System.Linq.Expressions.Expression.Convert(Expression expression, Type type, MethodInfo method)
       at Microsoft.EntityFrameworkCore.ChangeTracking.ListOfValueTypesComparer`2.CompareLambda(ValueComparer elementComparer) in /_/src/EFCore/ChangeTracking/ListOfValueTypesComparer.cs:line 68
       at Microsoft.EntityFrameworkCore.ChangeTracking.ListOfValueTypesComparer`2..ctor(ValueComparer elementComparer) in /_/src/EFCore/ChangeTracking/ListOfValueTypesComparer.cs:line 52
       at System.Reflection.MethodBaseInvoker.InvokeWithOneArg(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
    

    We have a simple query. Foo is in this case an int32?

    if(cirteria.Foo.HasValue)
    {
        from item in ourQuery where !item.Foo.HasValue || item.Foo == criteria.Foo.Value select item;
    }

    This also prevents us from updating from .Net8 to .Net9.

  16. ajcvickers commented on Dec 4, 2024

    @ajcvickers
    Contributor

    Note from team meeting: we will not patch this now, since following best practices as shown in the comment above should fix this issue.

    @ossendorf-at-hoelscher If you are still seeing an issue after defining non-nullable value type converters, then please open a new issue and attach a small, runnable project or post a small, runnable code listing that reproduces what you are seeing so that we can investigate.

  17. added this to the 10.0.0 milestone on Dec 4, 2024
  18. removed their assignment
    on Dec 11, 2024
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

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions