You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
No coercion operator is defined between nullable and not nullable type after upgrade from EFCore8 to EFCore9 #35117
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:newAreaLocationId(value.Value));
and in where linq clause I can write like this:
...var result =awaitdb....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.
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(varcontext=newContextOfDoom()){awaitcontext.Database.EnsureDeletedAsync();awaitcontext.Database.EnsureCreatedAsync();}using(varcontext=newContextOfDoom()){varavailableLocations=newList<AreaLocationId>{new(1),new(2)};varresult=awaitcontext.Set<Product>().Where(x =>x.LocationId!=null&&availableLocations.Contains(x.LocationId.Value)).ToListAsync();}publicclassContextOfDoom:DbContext{publicDbSet<Product>Products=>Set<Product>();protectedoverridevoidOnConfiguring(DbContextOptionsBuilderoptionsBuilder)=>optionsBuilder.EnableSensitiveDataLogging().LogTo(Console.WriteLine).UseSqlServer("Server=localhost;Database=DoomSlug;Trusted_Connection=True;TrustServerCertificate=True");protectedoverridevoidOnModelCreating(ModelBuildermodelBuilder){modelBuilder.Entity<Product>(b =>{b.Property(e =>e.LocationId).HasConversion(
id =>id==null?(int?)null:id.Value.Value,
value =>value==null?null:newAreaLocationId(value.Value));b.HasKey(e =>e.LocationId);});}}publicclassProduct{publicAreaLocationId?LocationId{get;set;}}publicreadonlyrecordstructAreaLocationId(intValue);
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.
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:
protectedclassAreaLocationIdConverter():ValueConverter<AreaLocationId,int>(v =>v.Value, v =>new(v));
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?
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.
Activity
ajcvickers commentedon Nov 15, 2024
Confirmed regression from EF8. Full repro below.
Full repro
dario-l commentedon Nov 15, 2024
Wow... serious issue as I can see. 😞
roji commentedon Nov 15, 2024
@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.
dario-l commentedon Nov 15, 2024
@roji Thanks for explanation. That's a relief. 👍🏻
rabberbock commentedon Nov 25, 2024
I also ran into a similar issue.
Because
numberis nullable this no longer works in EF Core 9 with the following error,Let me know if you think I should open a separate issue. Thanks!
roji commentedon Nov 25, 2024
@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.
rabberbock commentedon Nov 25, 2024
@roji Sure thing!
Here it is https://github.com/rabberbock/EfCore9RegressionNullable.
ajcvickers commentedon Nov 27, 2024
@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:
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 isAreaLocationId?. We either need better inference, or more forgiving collections.ajcvickers commentedon Nov 27, 2024
@rabberbock I moved your issue to #35227 since it is not the same as the issue reported here.
3 remaining items
ajcvickers commentedon Nov 28, 2024
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:
And then used like this:
ajcvickers commentedon Nov 30, 2024
Re-open to consider patching.
ossendorf-at-hoelscher commentedon Dec 2, 2024
We are experiencing the same exception but not with a collection.
We have a simple query.
Foois in this case anint32?This also prevents us from updating from .Net8 to .Net9.
ajcvickers commentedon Dec 4, 2024
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.