37

I used the database first approach. The model is right (or at least it looks like) But I always get this error. Please, I've already tried so many things.. The full code of my program (and even sql script by which I create my database) is here: https://github.com/AntonioParroni/test-task-for-backend-stack/blob/main/Server/Models/ApplicationContext.cs

Since I have a mac. I created my model with dotnet ef cli commands (dbcontext scaffold) I can use my context. But I can't touch any DbSet..

public static void Main(string[] args)
    {
        using (ApplicationContext context = new ApplicationContext())
        {
            Console.WriteLine(context.Database.CanConnect());
            var months = context.Months.ToList();
            foreach (var month in months)
            {
                Console.WriteLine(month.MonthName);
            }
        }
        //CreateHostBuilder(args).Build().Run();
    }

It is not my first time using EF. And everything was working fine before, in many simple projects or tasks. While here.... It doesn't matter what I do (I even tried to rename all of my columns name, erase all tables except one, modify the context code, use the same steps from this project on a new, totally empty project..) It is always..

Unhandled exception. System.TypeInitializationException: The type initializer for 'Microsoft.EntityFrameworkCore.Query.Internal.NavigationExpandingExpressionVisitor' threw an exception.
 ---> System.TypeInitializationException: The type initializer for 'Microsoft.EntityFrameworkCore.Query.QueryableMethods' threw an exception.
     ---> System.InvalidOperationException: Sequence contains more than one matching element
       at System.Linq.ThrowHelper.ThrowMoreThanOneMatchException() in System.Linq.dll:token 0x600041c+0xa
ect....

Here is my package reference file

"restore":{"projectUniqueName":"/Users/mac/Documents/GitHub/test-task-for-backend-stack/Server/Server.csproj",
    "projectName":"Server","projectPath":"/Users/mac/Documents/GitHub/test-task-for-backend-stack/Server/Server.csproj",
    "outputPath":"/Users/mac/Documents/GitHub/test-task-for-backend-stack/Server/obj/","projectStyle":
    "PackageReference","originalTargetFrameworks":["net6.0"],"sources":{"https://api.nuget.org/v3/index.json":{}},
    "frameworks":{"net6.0":{"targetAlias":"net6.0","projectReferences":{}}},
    "warningProperties":{"warnAsError":["NU1605"]}}"frameworks":{"net6.0":
        {"targetAlias":"net6.0","dependencies":{"EntityFramework":
            {"target":"Package","version":"[6.4.4, )"},
            "Microsoft.EntityFrameworkCore.Design":{"include":"Runtime, Build, Native, ContentFiles, Analyzers, BuildTransitive",
            "suppressParent":"All","target":"Package","version":"[5.0.0, )"},
            "Microsoft.EntityFrameworkCore.SqlServer":{"target":"Package","version":"[5.0.0, )"},
            "Swashbuckle.AspNetCore":{"target":"Package","version":"[5.6.3, )"}},
            "imports":["net461","net462","net47","net471","net472","net48"],
            "assetTargetFallback":true,"warn":true,
            "frameworkReferences":{"Microsoft.AspNetCore.App":{"privateAssets":"none"},
            "Microsoft.NETCore.App":{"privateAssets":"all"}},
        "runtimeIdentifierGraphPath":"/usr/local/share/dotnet/sdk/6.0.100-preview.6.21355.2/RuntimeIdentifierGraph.json"}}

It's been already a few days. And I'm becoming really confused and mad. Why is this happening.. and why there is not that much info about this type of error in the internet. Please, just point me in the right direction..

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
Savonarolla
  • 459
  • 1
  • 5
  • 10

1 Answers1

69

You have net6.0 target framework which is still not released while you have installed EF6 which is a previous iteration Entity Framework (mainly used with legacy .NET Framework projects) and you also have EF Core (a modern iteration of it) but older version - 5.0 (which you are actually using for your context, see the using Microsoft.EntityFrameworkCore; statements there).

Try removing EntityFramework package and installing preview version of Microsoft.EntityFrameworkCore.SqlServer (possibly just updating to the latest 5 version also can help) and either removing completely or installing preview version of Microsoft.EntityFrameworkCore.Design. (Also I would recommend to update your SDK to rc and install rc versions of packages).

Or try removing the reference to EntityFramework (not Core one) and changing target framework to net5.0 (if you have it installed on your machine).

As for why do you see this exception - I would guess it is related to the new methods added to Queryable in .NET 6 which made one of this checks to fail.

TL;DR

As mentioned in the comments - update EF Core to the corresponding latest version (worked for 5.0 and 3.1) or update to .NET 6.0 and EF Core 6.

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
  • 1
    Hmmm.... I did everything what you say (and also regenerated my models) Well... now I am having a different error. It is at least something. The navigation '' cannot be added because it targets the keyless entity type 'RegistrationCountByDevicesAndMonth'. Navigations can only target entity types with keys. Blah blah blah... I am going to add some keys to all the tables (yeah, forced good practices) Thank you. I am so messed up with all of these .NET versions, frameworks, cores, entities for both... ah.... – Savonarolla Sep 18 '21 at 18:37
  • Oh my goooshh... it works!!! May I kiss you ? You can't understand how grateful I am! Thank you sooo much!!! – Savonarolla Sep 18 '21 at 18:46
  • I love C#..... Now my whole webAPI project is not running.... crit: Microsoft.AspNetCore.Hosting.Diagnostics[6] Application startup exception System.TypeInitializationException: The type initializer for 'Microsoft.AspNetCore.Mvc.MvcCoreLoggerExtensions' threw an exception. WTF... Already created an empty project with dotnet new webapi --no-https And just installed the packages that you mentioned.. Exception... I didin't even touch the code at all... Just great( – Savonarolla Sep 18 '21 at 19:12
  • 2
    Huh... fixed it with 5.0.10 version of the packages that you mentioned. At least.. huuh – Savonarolla Sep 18 '21 at 19:18
  • @Savonarolla was glad to help and glad to hear that you have resolved all the problems! – Guru Stron Sep 18 '21 at 19:37
  • 2
    I was using .net 6.0 framework and .efcore 5.0.4 and got the same error. I backed my project down to 5.0 and got rid of the exception – Micah Armantrout Nov 10 '21 at 15:12
  • 9
    I was on 3.1.10 EF Core and netcore3.1 app. Updating to 3.1.21 fixed it – Ian Nov 11 '21 at 09:07
  • 11
    Thank you for the explanations. I updated .NET 5 projects to .NET 6 and had that EF error. When I updated all the NuGet packages to their latest .NET 6 version, it fixed it. – GerardF Nov 13 '21 at 15:37
  • It worked. As other folks here I was using .NET 6.0 with EF Core 5.0.4 and I was getting the same issue. Upgrading to EF Core 6.0.6 solved the issue. – Fabio Belz Jun 25 '22 at 20:58