【发布时间】:2021-09-18 16:07:02
【问题描述】:
我使用了数据库优先的方法。 该模型是正确的(或者至少看起来像) 但我总是得到这个错误。拜托,我已经尝试了很多东西.. 我的程序的完整代码(甚至是我创建数据库的 sql 脚本) 在这里:https://github.com/AntonioParroni/test-task-for-backend-stack/blob/main/Server/Models/ApplicationContext.cs
因为我有一个 mac。我使用 dotnet ef cli 命令(dbcontext 脚手架)创建了我的模型 我可以使用我的上下文。但我不能触摸任何 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();
}
这不是我第一次使用 EF。在许多简单的项目或任务中,一切都运行良好。在这里....不管我做什么(我什至尝试重命名我的所有列名,删除除一个之外的所有表,修改上下文代码,在一个新的、完全空的项目..) 它总是..
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....
这是我的包参考文件
"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"}}
已经好几天了。我变得非常困惑和疯狂。 为什么会发生这种情况..以及为什么互联网上没有太多关于此类错误的信息。请给我指出正确的方向..
【问题讨论】:
-
所以你的意思是即使
new ApplicationContext().Months.First()也会抛出错误? -
@CaiusJard 是的,当然。每次访问上下文中的 DbSet 都会引发此错误...
标签: c# sql-server entity-framework orm