Entity Framework | Sequence contains more than one matching element - c#

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..

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.

Related

Problem with HealthCheckers-UI after migration to .Net Core 6 [duplicate]

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..
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.

Accessing SQL from Entity Framework Core Queries in ASP.NET Core

In a post in the last week or so, someone made reference to a post: http://rion.io/2016/10/19/accessing-entity-framework-core-queries-behind-the-scenes-in-asp-net-core/
The blog outlined using internals of EF to show the generated SQL for a given EF query. Having a tool like this is invaluable, and will help my EF dev team to write better code. However, as it uses internal and unsupported code, it will not build using EF 2.1.4. The reference to RelationalQueryModelVisitor is now gone, and the code will not build.
I am using using .net core 2.1 as well.
Is there another or similar approach available?
Thanks.
Use the class in this link, which does work in .NET Core 2.1. Yes, I know you said you tried it, but I just tried it and it worked, so there must be something else going wrong in your project. Tell us the compiler error you are getting and we can help further.
Here is what I did:
Created a new ASP.NET Core project and made sure it's targetting .NET Core 2.1.
Added Microsoft.EntityFrameworkCore version 2.1.4 from NuGet.
Created an IQueryableExtensions class and pasted the code.
It compiles.
The RelationalQueryModelVisitor class does still exist in .NET Core 2.1. The documentation shows it is still there (notice the "Entity Framework Core 2.1" in the top left of the docs) and the current source code on GitHub still shows it there.
Would using their logging functionality be sufficient?
https://learn.microsoft.com/en-us/ef/core/miscellaneous/logging
public static readonly LoggerFactory MyLoggerFactory
= new LoggerFactory(new[] {new ConsoleLoggerProvider((_, __) => true, true)});
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder
.UseLoggerFactory(MyLoggerFactory) // Warning: Do not create a new ILoggerFactory instance each time
.UseSqlServer(...);
It's in the Microsoft.EntityFrameworkCore.Relational nuget package.

EF System.MissingMethodException

I have a problem in generating the EF model from Database SqlCe, in a c# project.
This is a new error because I've updated this many times in years.
I try many things to resolve it, also researching on the web, but nothing help me to resolve. I've changed also the NET Framework to 4.6.2.
The C# project uses NETFramework 4.5 and EF 6.2, EF.SqlCe 6.2.
This is the error message:
Generating the model took 00:00:30.5059377.
Unable to generate the model because of the following exception: 'System.MissingMethodException: Method not found: 'Boolean System.Data.Entity.Core.Common.DbProviderManifest.SupportsParameterOptimizationInSchemaQueries()'.
at Microsoft.Data.Entity.Design.VersioningFacade.ReverseEngineerDb.SchemaDiscovery.EntityStoreSchemaGeneratorDatabaseSchemaLoader.CreateFilteredCommand(String sql, String orderByClause, EntityStoreSchemaFilterObjectTypes queryTypes, List`1 filters, String[] filterAliases)
at Microsoft.Data.Entity.Design.VersioningFacade.ReverseEngineerDb.SchemaDiscovery.EntityStoreSchemaGeneratorDatabaseSchemaLoader.LoadDataTable[T](String sql, Func`2 orderByFunc, DataTable table, EntityStoreSchemaFilterObjectTypes queryTypes, IEnumerable`1 filters, String[] filterAliases)
at Microsoft.Data.Entity.Design.VersioningFacade.ReverseEngineerDb.SchemaDiscovery.EntityStoreSchemaGeneratorDatabaseSchemaLoader.LoadTableDetails(IEnumerable`1 filters)
at Microsoft.Data.Entity.Design.VersioningFacade.ReverseEngineerDb.SchemaDiscovery.EntityStoreSchemaGeneratorDatabaseSchemaLoader.LoadStoreSchemaDetails(IList`1 filters)
at Microsoft.Data.Entity.Design.VisualStudio.ModelWizard.Engine.ModelGenerator.GetStoreSchemaDetails(StoreSchemaConnectionFactory connectionFactory)
at Microsoft.Data.Entity.Design.VisualStudio.ModelWizard.Engine.ModelGenerator.CreateStoreModel()
at Microsoft.Data.Entity.Design.VisualStudio.ModelWizard.Engine.ModelGenerator.GenerateModel(List`1 errors)
at Microsoft.Data.Entity.Design.VisualStudio.ModelWizard.Engine.ModelBuilderEngine.GenerateModels(String storeModelNamespace, ModelBuilderSettings settings, List`1 errors)
at Microsoft.Data.Entity.Design.VisualStudio.ModelWizard.Engine.ModelBuilderEngine.GenerateModel(ModelBuilderSettings settings, IVsUtils vsUtils, ModelBuilderEngineHostContext hostContext)'.
Loading metadata from the database took 00:00:01.5131055.
Generating the model took 00:00:04.8109160.
Any idea?
Thank you very much
Running (as administrator) this command worked for me:
gacutil /u EntityFramework
A Visual Studio restart is needed then. The older version of assembly probably installed to GAC.
I have faced this issue using VS 2017. Below are the steps I have taken to get rid of this issue.
Go to "C:\Windows\Microsoft.NET\assembly\GAC_MSIL\EntityFramework"
folder location
Cut the "EntityFramework.dll" from the above folder
and kept somewhere
Go to the EF project and update the model without any error
Hope this will helps. Thanks.
I reinstalled VS 2017 and now works!!
In my case I had 2 packages referencing different versions of the same dll. For example the EntityFramework packages for mysql and sqlite referring to different versions of the EntityFramework core library
When viewed like that, the obvious fixes are to either
Remove one of the conflicting packages OR
Ensure that you select a version for both packages which references either the same or a compatible version of the conflicting dll. The Nuget package manager is useful in this regard.
Bear in mind that, once in a while, your IDE might need a restart to capture any changes.

SerializationStore not finding references

When trying to deserialize using the ComponentSerializationService, errors are populated that references were not found:
public ICollection Deserialize(object serializationData)
{
var serializationStore = serializationData as SerializationStore;
var componentSerializationService = _serviceProvider.GetService(typeof(ComponentSerializationService)) as ComponentSerializationService;
var collection = componentSerializationService.Deserialize(serializationStore);
}
Errors such as :
Could not find type 'System.Drawing.Size'. Please make sure that the
assembly that contains this type is referenced. If this type is a
part of your development project, make sure that the project has been
successfully built using settings for your current platform or Any
CPU.
Here I've passed through a Button control and set the size property.
I remember that I had this "could not find type System.Drawing.Size" some time back and that I spent way too many hours fixing it. I don't really remember what it was that finally fixed it and I don't think that choosing Any CPU is a problem at all. Although it wasn't the very same context as yours I still think it's worth trying the following since it could be a problem connected to referencing different versions of the System.Drawing.dll from several projects inside your solution.
Thus, try double checking the solution for inconsistencies in the versions used (even if the packages.config entries are looking ok) and make sure they all are referencing the same version (.net461 for example).
In my case, some of the 30+ libraries in the solution turned out to be using .net45; I used a tool called Target Framework Migrator to fix this. You can get it through Tools => extensions and updates => Online => Visual Studio Gallery
and then type Target Framework Migrator in the Search Field.
I do remember, that I also upgraded .Net to 4.6.1 during my attempts to fix the problem ... maybe you could try this too ... but in any case running the Target Framework Migrator for your own Libraries (and restarting VS 2015 on the way) is definitely worth a try.
Good luck!

Entity Framework 4.3 doesn't create database

I created new project and added the newest entity framework to it (version 4.3). I created classes and the context as in previous EF versions. However, during the very first run when the database should be created (in my case it is SQL Server 2005), I'm receiving the following error:
An error occurred while executing the command definition. See the inner exception for details.
With the following inner exception:
Invalid object name 'dbo.__MigrationHistory'.
As I understand, this table is for migrations, but this table does not exist if there is no database. Am I doing something wrong?
More info:
For testing purposes I created only one class:
public class Test
{
[Key]
public int TestId { get; set;}
public string Name {get; set;}
}
public class Context : DbContext
{
public Context() : base("MyConnection")
{
}
public DbSet<Test> Tests { get; set;}
}
UPDATE 1
After some tests I realized that application is throwing unhandled exception from visual studio and break in visual studio. The exception was System.Data.EntityCommandExecutionException. Once I ignored that expection and didn't stop code execution, database was created.
UPDATE 2
After another few hours working with database I found out that playing with Enable-Migrations option and Update-Database from console also is solving that issue. It is creating database before application start and don't break in Visual Studio.
Could you try removing your constructor to make EF use it's default connection string.
public Context() : base("MyConnection")
{
}
Failing that, could you try updating your database from the Package Manager Console to see if you get any further information.
Update-Database -Verbose
Possibly unrelated in your case, but I get the same error when using MvcMiniProfiler 1.9. If you are using it too, make sure EF profiling is turned off by commenting out the line:
//MiniProfilerEF.Initialize();
Within the MiniProfiler App_Start.
For others experiencing a similar issue, I have found that reenabling migrations from the Package Manager Console can help in certain cases. Make sure you have a copy of your Migration configuration before doing this.
Enable-Migrations -Force
...and just to add one more possible answer for all those facing similar problem
(note: this is an open-ended story seems, as there're obviously some bugs still with the migration part)...
This link came closest to what I needed
Error when running Update-Database with EF 4.3
so, you need to do 3 things (in that order - and I'm referring to an existing project):
(all is in PM console)
Make sure that 'default project' in PM Console is set to your desired project (i.e. for larger solutions) - that doesn't necessarily match your startup project! (and closely watch the comments/response in PM as to whether the actions were made on the project you want)
(1) Enable-Migrations -force
(2) Add-Migration Initial
(3) Update-Database -Verbose
...if you still get an exception in PM console
(4) then you might need to 'move' your project into the root
it sounds silly I know, but that was the main problem on my side - I had a bunch of solution folders and any of the above would fail on projects within solution folders. However, once I moved the project to the root, everything worked fine (no more exceptions, with or w/o first-chance exceptions for CLR turned on or off)...
hope this helps somebody
EDIT: if your data model project (EF CF) is a library - then set that project as a 'default project' in PM console - and run all those things above on that project directly (and have migration configuration etc. created in the lib itself). Otherwise it'd fail (and the same no MigrationHistory exception also appears when your model is a lib - and no migration defined for it, within it - and you have migration defined on the 'main project').
EDIT: you'd need to move both the lib (EF model) and the 'startup' project (calling it) into the root.

Categories

Resources