Entity Framework setup issue - c#

When I run my code
using (foodEntities db_Linq = new foodEntities())
{
return db_Linq.Database.Exists();
//return db_Linq.Foods.Any();
}
I keep getting this error in the output window.
A first chance exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll
What could be the issue? DB Credentials in web.config?
Other info:
I actually have 2 projects in my solution. One's a class library, the other MVC 4 web project.
Class library uses Entity Framework connection. Web project uses ADO connection string.
The above issue happens when web project calls the class library.
The code given above is from class library.

What version of the EF are you using? It seemed to me that you use EF6 and you have issues with the namespaces.
Please, check Updating Applications to use EF6 link. The main part for you is "Update namespaces for any core EF types being used"

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.

Entity Framework | Sequence contains more than one matching element

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.

Scaffolding in .Net Core with Multiple Projects in Solution

I have created an .Net Core MVC6 application targeting net461. I have used a project structure I am very familiar with in which I place the data, model, and service classes in separate class library projects and the Web project references these.
When I attempt to scaffold a controller I receive an error that multiple matching types exist for the model I am scaffolding.
If I move all code to a single project, scaffolding is successful. If I move the context to Web project and leave the model in a separate project, I receive an error the NO matching types were found.
Has anyone else seen this same issue? Is there a workaround to still use this type of architecture?
Update
I started another project and always get this issue. I get this error when only using 1 extra project for the models. Attached is the error I recieve.
Scaffolding Error
Update 2
When the context and model are in the same project I receive this error.
Error editing dbContext
Cannot post a comment, so I've to write an answer instead. I also had the same issue and opened it on Scaffolding github repository. Here's the response:
currently there is an issue with scaffolding, that it doesn't support
model classes outside of the current project properly.
As a workaround, you can add the model temporarily to your web project
and then move it to the BLL/ DAL projects after scaffolding.
Plus they also opened this issue as a bug, quoting:
Scaffolding fails if model class is in a dependency (project/ library)
of the project on which scaffolding is being run. #251
Project A has a dependeny on Project B. Project B has model class If
you try to run scaffolding on Project A by using model class from
Project B, it fails with the below error: No model type returned for
type:
Hence, as of RC2, this is a bug in scaffolding tooling.

Reference an EF5 project from an EF6 project

Is it possible to use a project that was written and built using Entity Framework 5 as a reference in a project that uses Entity Framework 6? When doing so, I get "Method not found" errors on functionality that has been deprecated in EF6, but that works just fine when used in the EF5 project as a standalone project.
A call like this:
dataContext.Database.SqlQuery()
throws an error of:
{"Method not found: 'System.Collections.Generic.IEnumerable`1<!!0> System.Data.Entity.Database.SqlQuery(System.String, System.Object[])'."} System.Exception {System.MissingMethodException}

Entity Framework code first migration throws exception

I have an asp.net MVC application using entity framework code first in which I have 3 projects. One is a class library project in which I put my Domain objects and DataContext class. In another project I put my admin MVC project, and the third project is the front end MVC application. I created a reference to my Domain project in my MVC application.
I enabled code first migration on my Domain object class library project and added first migrations initialCreate. Then I executed Update-database command. The database is created and my admin MVC application is able to access the data and everything is good. But when I rebuild my Domain object class library project the MVC application throws an exception as follows:
An exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll but was not handled in user code
Additional information: The model backing the 'BookManyContext'
context has changed since the database was created. Consider using
Code First Migrations to update the database
(http://go.microsoft.com/fwlink/?LinkId=238269).
But actually I won't touch my domain object nor context class. Even my MVC application won't access the data, and throws the exception.
What's wrong with my approach?
Do I need to put my Context class in a separate project?

Categories

Resources