Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

System.TypeInitializationException: The type initializer for 'Microsoft.EntityFrameworkCore.Query.QueryableMethods' threw an exception. #25182

Closed
pdecostervgls opened this issue Jul 1, 2021 · 20 comments

Comments

@pdecostervgls
Copy link

pdecostervgls commented Jul 1, 2021

File a bug

During the upgrade of a NuGet package, I find myself unable to run my app anymore because of this exception. I am unable to provide a working reproducable sample but I am mostly looking for guidance on what troubleshooting steps I can take to resolve this issue, since it is most probably related to the configuration.

The app in question is a Uno Platform app, and contains a subproject for processing an iOS intent.

Both the iOS and intents project are using

  • Microsoft.EntityFrameworkCore 5.0.7
  • Microsoft.EntityFrameworkCore.Sqlite 5.0.7

Stack traces

System.TypeInitializationException: The type initializer for 'Microsoft.EntityFrameworkCore.Query.QueryableMethods' threw an exception. ---> System.Collections.Generic.KeyNotFoundException: The given key 'All' was not present in the dictionary.
  at System.Collections.Generic.Dictionary`2[TKey,TValue].get_Item (TKey key) [0x0001e] in <da8885cdf78b449d96de00cdb9d47225>:0 
  at Microsoft.EntityFrameworkCore.Query.QueryableMethods.<.cctor>g__GetMethod|185_58 (System.String name, System.Int32 genericParameterCount, System.Func`2[T,TResult] parameterGenerator, Microsoft.EntityFrameworkCore.Query.QueryableMethods+<>c__DisplayClass185_0& ) [0x00014] in <4d1f22249bbe4676a871766038953138>:0 
  at Microsoft.EntityFrameworkCore.Query.QueryableMethods..cctor () [0x00052] in <4d1f22249bbe4676a871766038953138>:0 
   --- End of inner exception stack trace ---
  at Microsoft.EntityFrameworkCore.Query.Internal.QueryableMethodNormalizingExpressionVisitor.VisitMethodCall (System.Linq.Expressions.M<…>

Include provider and version information

EF Core version: 5.0.7
Database provider: Microsoft.EntityFrameworkCore.Sqlite
Target framework: Not sure
Operating system: MacOS Big Sur 11.4
IDE: Visual Studio for Mac 8.10.4 (build 11)

@pdecostervgls
Copy link
Author

Just realized, this would be better suited under the "Question" type, my apologies for that. Can anyone move it or should I file another issue under the right category?

@bricelam
Copy link
Contributor

bricelam commented Jul 2, 2021

What are the previous versions of the packages you upgraded?

Something in this code isn't working on iOS:

var queryableMethodGroups = typeof(Queryable)
.GetMethods(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly)
.GroupBy(mi => mi.Name)
.ToDictionary(e => e.Key, l => l.ToList());

Possibly caused by too much of the assembly getting trimmed at runtime (see also #10963)

@ibocon
Copy link

ibocon commented Jul 9, 2021

Having same issue.

System.Collections.Generic.KeyNotFoundException: The given key 'All' was not present in the dictionary.

It happens when I call DbSet<TItem>.ToList() only on iOS.

I followed source code and I can not get it because it should work on both platform, Android and iOS but only Android works.

I can find a method named All in Queryable. But why reflection can not find that only in iOS?

All = GetMethod(nameof(Queryable.All), 1,
types => new[]
{
typeof(IQueryable<>).MakeGenericType(types[0]),
typeof(Expression<>).MakeGenericType(typeof(Func<,>).MakeGenericType(types[0], typeof(bool)))
});

code queryableMethodGroups[name] throws KeyNotFoundException.

MethodInfo GetMethod(string name, int genericParameterCount, Func<Type[], Type[]> parameterGenerator)
=> queryableMethodGroups[name].Single(
mi => ((genericParameterCount == 0 && !mi.IsGenericMethod)
|| (mi.IsGenericMethod && mi.GetGenericArguments().Length == genericParameterCount))
&& mi.GetParameters().Select(e => e.ParameterType).SequenceEqual(
parameterGenerator(mi.IsGenericMethod ? mi.GetGenericArguments() : Array.Empty<Type>())));

dotnet/runtime System.Linq.Queryable

[DynamicDependency("All`1", typeof(Enumerable))]
public static bool All<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate)
{
    if (source == null)
        throw Error.ArgumentNull(nameof(source));
    if (predicate == null)
        throw Error.ArgumentNull(nameof(predicate));
    return source.Provider.Execute<bool>(
        Expression.Call(
            null,
            CachedReflectionInfo.All_TSource_2(typeof(TSource)),
            source.Expression, Expression.Quote(predicate)
            ));
}

https://github.com/dotnet/runtime/blob/b2a5499230f005108b882ac8bd76b3868d2573e4/src/libraries/System.Linq.Queryable/src/System/Linq/Queryable.cs#L1500-L1513

Is there any workaround?

@my1184
Copy link

my1184 commented Jul 14, 2021

We ran into this issue with Xamarin but only in iOS Release configuration. Our workaround is to specify some linking skip settings in the iOS Build properties under "Additional mtouch arguments"

--optimize=experimental-xforms-product-type --linkskip=System.Core --linkskip=mscorlib

@AndriySvyryd
Copy link
Member

@JeremyLikness Could you try to repro this?

@JeremyLikness
Copy link
Member

@AndriySvyryd I can see if I can replicate it on Windows, but I don't have a Mac.

@smitpatel
Copy link
Member

I have a mac, I can help out if you have some repro steps to try and play around.

@JeremyLikness
Copy link
Member

Sounds good. I will reach out with some details.

@flimtix
Copy link

flimtix commented Sep 24, 2021

System.Collections.Generic.KeyNotFoundException: The given key 'All' was not present in the dictionary.

I get the same error message in combination with Xamarin. Is there an update for this in the meantime?

Is this error similar with this one:
#3394

@ajcvickers
Copy link
Member

@smitpatel @JeremyLikness Any update here?

@ajcvickers ajcvickers assigned smitpatel and JeremyLikness and unassigned roji Oct 5, 2021
@ajcvickers
Copy link
Member

/cc @bricelam

@ajcvickers ajcvickers assigned bricelam and unassigned smitpatel and JeremyLikness Oct 5, 2021
@flimtix
Copy link

flimtix commented Oct 11, 2021

Is there any update on this bug?

Are there any updates on this bug yet as I am currently stuck?

Since I get exactly the same error I assume the author is also using Xamarin in combination with EF Core / SQLite.

If more info is needed, I have simplified a method from my project and pasted it here.
When I test it on a simulator or real device I get no errors. As soon as I load the app into the app store and test it via Testflight I get the above error.

        private static IEnumerable<T> GetFooKey<T>(int keyKind, Expression<Func<KeyUsage, bool>> filter = null) where T : class, new()
        {
            using (MobileDbContext ctx = GetMobileDbContext())
            {
                IQueryable<KeyUsage> query = ctx.KeyUsage.Where(use => use.KeyKind == keyKind);
                if (filter != null)
                {
                    query = query.Where(filter);
                }

                List<T> fooList = new List<T>();
                foreach (KeyUsage itemKey in query.OrderByDescending(use => use.UsageCount).Take(20)?.ToList())
                {
                    T item = ctx.Find<T>(itemKey.Id);
                    if (item is null)
                    {
                        ctx.KeyUsage.Remove(itemKey);
                    }
                    else
                    {
                        fooList.Add(item);
                    }
                }

                ctx.SaveChanges();
                return fooList;
            }
        }

Nuget Packages
(Microsoft.EntityFrameworkCore / 3.1.19)
(Microsoft.EntityFrameworkCore.Sqlite / 3.1.19)
And also:
(Microsoft.EntityFrameworkCore / 5.0.11)
(Microsoft.EntityFrameworkCore.Sqlite / 5.0.11)

@flimtix
Copy link

flimtix commented Oct 13, 2021

I continued testing and also installed the latest EF Core version (5.0.11).
In the debugger everything runs as planned and without problems. But as soon as I switch to Release this error occurs.

So far I have changed the linking behavior to Link All, Link SKD only and Dont Link.

@bricelam
Copy link
Contributor

bricelam commented Oct 21, 2021

Until we address issue #21894, we recommend disabling the linker entirely:

<PropertyGroup>
  <PublishTrimmed>False</PublishTrimmed>
</PropertyGroup>

@flimtix
Copy link

flimtix commented Oct 27, 2021

@bricelam @ajcvickers

<PropertyGroup>
  <PublishTrimmed>False</PublishTrimmed>
</PropertyGroup>

Do I need to set Linking Behavior to Don't Link for this to work? If not on what then?
When I add this to my .csproj with Link SDK Only I'm getting the same error...

@flimtix
Copy link

flimtix commented Oct 28, 2021

I have found a solution that does not require disabling the linker. You can look at that workaround here.

@MichaelL79
Copy link

@bricelam @ajcvickers

<PropertyGroup>
  <PublishTrimmed>False</PublishTrimmed>
</PropertyGroup>

Do I need to set Linking Behavior to Don't Link for this to work? If not on what then? When I add this to my .csproj with Link SDK Only I'm getting the same error...

Did it work with Don't Link?

@flimtix
Copy link

flimtix commented Dec 12, 2021

@MichaelL79 Yes, It does work. But then your application size will be gigant and you may get errors when uploading to the AppStore...

@michaldivis
Copy link

Hi, I've been able to resolve this issue by telling the linker to skip the System.Core assembly (as the EF Core documentation says).

I've set the Linking behavior to SDK Only and added this to the Additional mtouch arguments:

--linkskip System.Core

@moraismateus
Copy link

Hi, I've been able to resolve this issue by telling the linker to skip the System.Core assembly (as the EF Core documentation says).

I've set the Linking behavior to SDK Only and added this to the Additional mtouch arguments:

--linkskip System.Core

Thank you michaldivis, that worked well for me.

@ajcvickers ajcvickers reopened this Oct 16, 2022
@ajcvickers ajcvickers closed this as not planned Won't fix, can't repro, duplicate, stale Oct 16, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests