使用Entity Framework Core创建Razor页面遇null参数错误如何解决?
解决ASP.NET Core 6 Razor Pages EF CRUD搭建时的「value cannot be null (parameter name: unconfiguredProjectCommonServices)」错误
错误成因
该错误源于项目代码生成工具与EF依赖包版本不匹配,或是Visual Studio代码生成服务初始化异常,常见于使用VS 2022的「添加新搭建项」功能创建CRUD页面时。
修复步骤
- 统一NuGet包版本:你当前
Microsoft.VisualStudio.Web.CodeGeneration版本为6.0.16,其余EF相关包均为6.0.27,版本不一致会引发依赖冲突。将Microsoft.VisualStudio.Web.CodeGeneration升级至6.0.27,确保所有相关包版本完全一致。 - 清理重建项目并重启VS:右键项目选择「清理」→「生成」,随后重启Visual Studio,清除工具缓存。
- 检查.csproj配置:确认项目文件中
TargetFramework为net6.0,且所有NuGet包版本统一,示例配置如下:<TargetFramework>net6.0</TargetFramework> <PackageReference Include="Microsoft.EntityFrameworkCore" Version="6.0.27" /> <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="6.0.27"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> </PackageReference> <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="6.0.27" /> <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="6.0.27"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> </PackageReference> <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration" Version="6.0.27" /> - 改用CLI命令生成CRUD:若VS UI工具仍异常,通过.NET CLI手动生成(替换
YourDbContext和YourEntity为实际类名):dotnet aspnet-codegenerator razorpage -m YourEntity -dc YourDbContext -udl -outDir Pages/YourEntity - 修复VS代码生成组件:打开Visual Studio Installer,修改VS 2022安装,确保「ASP.NET和Web开发」工作负载下的「代码生成器工具」已勾选,完成安装后重启VS。
额外排查
若上述步骤无效,创建全新的ASP.NET Core 6 Razor Pages项目,安装相同版本NuGet包后尝试生成CRUD页面,排查原项目是否存在配置损坏问题。
内容的提问来源于stack exchange,提问作者Hiệp Nguyễn
相关产品推荐
相关产品推荐

