Bug #92987 Entity Framework crashing when using linq Any() method

Submitted: 29 Oct 2018 12:57 Modified: 27 May 2019 10:25
Reporter: Manuel Zulian Email Updates:
Status: Verified Impact on me:
None 
Category:Connector / NET Severity:S3 (Non-critical)
Version:8.0.13, 8.0.16 OS:Windows
Assigned to: CPU Architecture:x86
Tags: ANY, EF, linq

[29 Oct 2018 12:57] Manuel Zulian
Description:
Starting from a basic console application, adding only mysql.data.entityframeworkcore package and entityframework.design (for scaffolding), calling the Any() method from linq on a table to check for existence of records throws this exception:

System.InvalidOperationException: 'No coercion operator is defined between types 'System.Int16' and 'System.Boolean'.'

		StackTrace	"   at System.Linq.Expressions.Expression.GetUserDefinedCoercionOrThrow(ExpressionType coercionType, Expression expression, Type convertToType)\r\n   at System.Linq.Expressions.Expression.Convert(Expression expression, Type type, MethodInfo method)\r\n   at Microsoft.EntityFrameworkCore.Storage.TypedRelationalValueBufferFactoryFactory.CreateGetValueExpression(Expression dataReaderExpression, Expression indexExpression, TypeMaterializationInfo materializationInfo, Boolean box)\r\n   at System.Linq.Enumerable.SelectIterator[TSource,TResult](IEnumerable`1 source, Func`3 selector)+MoveNext()\r\n   at System.Collections.Generic.LargeArrayBuilder`1.AddRange(IEnumerable`1 items)\r\n   at System.Collections.Generic.EnumerableHelpers.ToArray[T](IEnumerable`1 source)\r\n   at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)\r\n   at System.Dynamic.Utils.CollectionExtensions.ToReadOnly[T](IEnumerable`1 enumerable)\r\n   at System.Linq.Expressions.Expression.NewArrayInit(Type type, IEnumerable`1 initializers)\r\n   at Microsoft.EntityFrameworkCore.Storage.TypedRelationalValueBufferFactoryFactory.CreateArrayInitializer(CacheKey cacheKey)\r\n   at Microsoft.EntityFrameworkCore.Storage.TypedRelationalValueBufferFactoryFactory.<Create>b__10_0(CacheKey k)\r\n   at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)\r\n   at Microsoft.EntityFrameworkCore.Internal.NonCapturingLazyInitializer.EnsureInitialized[TParam,TValue](TValue& target, TParam param, Func`2 valueFactory)\r\n   at Microsoft.EntityFrameworkCore.Query.Internal.ShaperCommandContext.NotifyReaderCreated(DbDataReader dataReader)\r\n   at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.BufferlessMoveNext(DbContext _, Boolean buffer)\r\n   at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.MoveNext()\r\n   at Microsoft.EntityFrameworkCore.Query.QueryMethodProvider.GetResult[TResult](IEnumerable`1 valueBuffers, Boolean throwOnNullResult)\r\n   at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ResultEnumerable`1.GetEnumerator()\r\n   at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.MoveNext()\r\n   at System.Linq.Enumerable.TryGetFirst[TSource](IEnumerable`1 source, Boolean& found)\r\n   at System.Linq.Enumerable.First[TSource](IEnumerable`1 source)\r\n   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass15_1`1.<CompileQueryCore>b__0(QueryContext qc)\r\n   at System.Linq.Queryable.Any[TSource](IQueryable`1 source)\r\n   at AnyBugTest.Program.Main(String[] args) in C:\\Users\\****\\source\\repos\\AnyBugTest\\AnyBugTest\\Program.cs:line 14"	string

(using the any() from Microsoft.EntityFrameworkCore.Internal looks fine but it seems to be deprecated)

Example code:

using System;
using System.Linq;
using AnyBugTest.Models.Ctx;

namespace AnyBugTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            var ctx = new Ctx();
            if(ctx.table.Any())
                Console.WriteLine("test");
        }
    }
}

How to repeat:
See description.
[3 Nov 2018 17:40] Bradley Grainger
Are you trying to map a BIT(1) column to bool? If so, see my comment on bug #93028.
[3 Nov 2018 17:42] Manuel Zulian
No, it's TINYINT(1).
[13 Nov 2018 18:15] Oliver Hall
I'm hitting the same issue, though I'm not creating any code myself.  I'm using migrations to add ASP.Net Identity to a MySQL schema.

[System.InvalidOperationException: No coercion operator is defined between types 'System.Int16' and 'System.Boolean'.]

The MySQL datatype for the generated tables is BIT(1) for all boolean properties (none of which are nullable) and I'm calling UserManager.FindByEmailAsync(...) which in turn calls Linq.

I can't see where the Int16 is coming from at all.

Apologies if I'm missing something obvious, or there's an easy way to add user-defined coercion, but I'm pretty new to Entity Framework.  Unfortunately, this is blocking further progress for me.
[12 Dec 2018 15:30] Andrew Furniss
I am also experiencing this issue since upgrading to MySQL Server 8 from 5.7. I'm on Windows and using MySQL.Data.EntityFrameworkCore 8.0.13 nuget package within a .NET Core Web API application.
[2 Apr 2019 8:30] Marcos Gomes
Hi, I've notice that on MySQLTypeMapper if we change the _bit mapping to something like this:
private readonly RelationalTypeMapping _bit = new MySQLNumberTypeMapping("bit", typeof(bool), DbType.Boolean);
Ir resolves the error.

O hope the dev team could look at that.
Thanks
[10 May 2019 13:03] Jo kjhjkh
I have the same issue, 

It's weird where, select etc is working except any()...

I'm using connector/framework core 8.0.16. My server also is running on 8.0.16

My type in the database is : tinyint(1)

Here is my model

        [Column(TypeName = "TINYINT(1)")]
        public bool deleted { get; set; }

And I got this error using Any
No coercion operator is defined between types 'System.Int16' and 'System.Boolean'.
[10 May 2019 13:05] Jo kjhjkh
Here is my call when it crash

var users = dbContext.user.Any(x => !x.deleted);
[10 May 2019 13:07] Jo kjhjkh
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 System.Linq.Expressions.Expression.Convert(Expression expression, Type type)
   at Microsoft.EntityFrameworkCore.Storage.TypedRelationalValueBufferFactoryFactory.CreateGetValueExpression(Expression dataReaderExpression, Int32 index, TypeMaterializationInfo materializationInfo, Boolean detailedErrorsEnabled, Boolean box)
   at Microsoft.EntityFrameworkCore.Storage.TypedRelationalValueBufferFactoryFactory.<>c__DisplayClass13_0.<CreateArrayInitializer>b__0(TypeMaterializationInfo mi, Int32 i)
   at System.Linq.Enumerable.SelectIterator[TSource,TResult](IEnumerable`1 source, Func`3 selector)+MoveNext()
   at System.Collections.Generic.LargeArrayBuilder`1.AddRange(IEnumerable`1 items)
   at System.Collections.Generic.EnumerableHelpers.ToArray[T](IEnumerable`1 source)
   at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
   at System.Dynamic.Utils.CollectionExtensions.ToReadOnly[T](IEnumerable`1 enumerable)
   at System.Linq.Expressions.Expression.NewArrayInit(Type type, IEnumerable`1 initializers)
   at Microsoft.EntityFrameworkCore.Storage.TypedRelationalValueBufferFactoryFactory.CreateArrayInitializer(CacheKey cacheKey, Boolean detailedErrorsEnabled)
   at Microsoft.EntityFrameworkCore.Storage.TypedRelationalValueBufferFactoryFactory.<Create>b__11_0(CacheKey k)
   at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
   at Microsoft.EntityFrameworkCore.Storage.TypedRelationalValueBufferFactoryFactory.Create(IReadOnlyList`1 types)
   at Microsoft.EntityFrameworkCore.Query.Sql.DefaultQuerySqlGenerator.CreateValueBufferFactory(IRelationalValueBufferFactoryFactory relationalValueBufferFactoryFactory, DbDataReader dataReader)
   at Microsoft.EntityFrameworkCore.Query.Internal.ShaperCommandContext.<NotifyReaderCreated>b__14_0(FactoryAndReader s)
   at Microsoft.EntityFrameworkCore.Internal.NonCapturingLazyInitializer.EnsureInitialized[TParam,TValue](TValue& target, TParam param, Func`2 valueFactory)
   at Microsoft.EntityFrameworkCore.Query.Internal.ShaperCommandContext.NotifyReaderCreated(DbDataReader dataReader)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.BufferlessMoveNext(DbContext _, Boolean buffer)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.MoveNext()
   at Microsoft.EntityFrameworkCore.Query.QueryMethodProvider.GetResult[TResult](IEnumerable`1 valueBuffers, Boolean throwOnNullResult)
   at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ResultEnumerable`1.GetEnumerator()
   at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.MoveNext()
   at System.Linq.Enumerable.TryGetFirst[TSource](IEnumerable`1 source, Boolean& found)
   at System.Linq.Enumerable.First[TSource](IEnumerable`1 source)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass15_1`1.<CompileQueryCore>b__0(QueryContext qc)
   at System.Linq.Queryable.Any[TSource](IQueryable`1 source, Expression`1 predicate)
   at test.Controllers.UserController.Get(UInt32 id) in F:\Documents\test\fdet.backend\Controllers\UserController.cs:line 92
[27 May 2019 10:25] MySQL Verification Team
Hello Manuel Zulian,

Thank you for the report.
Verified as described with VS 2019, C/NET 8.0.16 on Win10.

regards,
Umesh
[29 Jun 2019 9:59] Kok How Teh
Any ETA for the fix?
[3 Jul 2019 10:33] Luca Graziani
Hi, I've same problem with IQueryable<T>.Any call.
In my specific case I've extended identity framework to support client management.
This is my stack trace:

System.InvalidOperationException: No coercion operator is defined between types 'System.Int16' and 'System.Boolean'.
   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 System.Linq.Expressions.Expression.Convert(Expression expression, Type type)
   at Microsoft.EntityFrameworkCore.Storage.TypedRelationalValueBufferFactoryFactory.CreateGetValueExpression(Expression dataReaderExpression, Int32 index, TypeMaterializationInfo materializationInfo, Boolean detailedErrorsEnabled, Boolean box)
   at Microsoft.EntityFrameworkCore.Storage.TypedRelationalValueBufferFactoryFactory.<>c__DisplayClass13_0.<CreateArrayInitializer>b__0(TypeMaterializationInfo mi, Int32 i)
   at System.Linq.Enumerable.SelectIterator[TSource,TResult](IEnumerable`1 source, Func`3 selector)+MoveNext()
   at System.Collections.Generic.LargeArrayBuilder`1.AddRange(IEnumerable`1 items)
   at System.Collections.Generic.EnumerableHelpers.ToArray[T](IEnumerable`1 source)
   at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
   at System.Dynamic.Utils.CollectionExtensions.ToReadOnly[T](IEnumerable`1 enumerable)
   at System.Linq.Expressions.Expression.NewArrayInit(Type type, IEnumerable`1 initializers)
   at Microsoft.EntityFrameworkCore.Storage.TypedRelationalValueBufferFactoryFactory.CreateArrayInitializer(CacheKey cacheKey, Boolean detailedErrorsEnabled)
   at Microsoft.EntityFrameworkCore.Storage.TypedRelationalValueBufferFactoryFactory.<Create>b__11_0(CacheKey k)
   at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
   at Microsoft.EntityFrameworkCore.Storage.TypedRelationalValueBufferFactoryFactory.Create(IReadOnlyList`1 types)
   at Microsoft.EntityFrameworkCore.Query.Sql.DefaultQuerySqlGenerator.CreateValueBufferFactory(IRelationalValueBufferFactoryFactory relationalValueBufferFactoryFactory, DbDataReader dataReader)
   at Microsoft.EntityFrameworkCore.Query.Internal.ShaperCommandContext.<NotifyReaderCreated>b__14_0(FactoryAndReader s)
   at Microsoft.EntityFrameworkCore.Internal.NonCapturingLazyInitializer.EnsureInitialized[TParam,TValue](TValue& target, TParam param, Func`2 valueFactory)
   at Microsoft.EntityFrameworkCore.Query.Internal.ShaperCommandContext.NotifyReaderCreated(DbDataReader dataReader)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.BufferlessMoveNext(DbContext _, Boolean buffer)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.MoveNext()
   at Microsoft.EntityFrameworkCore.Query.QueryMethodProvider.GetResult[TResult](IEnumerable`1 valueBuffers, Boolean throwOnNullResult)
   at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ResultEnumerable`1.GetEnumerator()
   at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.MoveNext()
   at System.Linq.Enumerable.TryGetFirst[TSource](IEnumerable`1 source, Boolean& found)
   at System.Linq.Enumerable.First[TSource](IEnumerable`1 source)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass15_1`1.<CompileQueryCore>b__0(QueryContext qc)
   at System.Linq.Queryable.Any[TSource](IQueryable`1 source, Expression`1 predicate)
   at Common.IdentityServerRepository.MySQL.MyClientManager.ExistsAsync(String clientId) in C:\Users\Developer\Documents\Visual Studio 2019\Projects\Test\Common.IdentityServerRepository.MySQL\MyClientManager.cs:line 37
   at Membership.Web.Controllers.HomeController.Index() in C:\Users\Developer\Documents\Visual Studio 2019\Projects\Test\Membership.Web\Controllers\HomeController.cs:line 23
   at Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at System.Threading.Tasks.ValueTask`1.get_Result()
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeActionMethodAsync()
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeNextActionFilterAsync()
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync()
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter()
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()
   at Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
[3 Jul 2019 10:45] Luca Graziani
Test Application with issue

Attachment: Test.zip (application/x-zip-compressed, text), 613.65 KiB.

[17 Jul 2019 7:34] MySQL Verification Team
Bug #96228 marked as duplicate of this one
[13 Oct 2019 12:54] Enrique Penabella
I also found this to be an issue using linq 'Any()'

I switched to 'FirstOrDefault() is null' instead unfortunately and it worked :)
[29 Jan 2020 7:24] Luca Graziani
Hi!
As Enrique Penabella I've created a simple extension method to trace the existence of item.
This is the code:

public static class ExistsExtension
    {
        public static bool Exists<TSource> (this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate)
        {
            if (source.FirstOrDefault(predicate) == null)
                return false;

            return true;
        }
    }

It's a simple workaround, but works well :D.

Portions of this website are copyright © 2001, 2002 The PHP Group

Page generated in 0.072 sec. using MySQL 8.4.7-u6-cloud

Timestamp references displayed by the system are UTC.
Content reproduced on this site is the property of the respective copyright holders.
It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party.