ASP.NET Core 5.0.9结合EntityFrameworkCore 5.0.9生成新Razor页面时异常问题咨询
我来帮你梳理下这个问题——脚手架自动降级包版本、程序集加载失败,还有空引用错误,本质都是版本不匹配导致的连锁反应。试试下面这些步骤,应该能解决:
1. 强制统一项目所有EF相关包版本
打开你的项目文件(.csproj),手动把所有EF Core系列包的版本都锁定为5.0.9,包括间接依赖的部分。确保你的项目文件里的引用看起来像这样:
<PropertyGroup> <TargetFramework>net5.0</TargetFramework> </PropertyGroup> <ItemGroup> <!-- 核心EF包 --> <PackageReference Include="Microsoft.EntityFrameworkCore" Version="5.0.9" /> <!-- 设计时工具,用于脚手架生成 --> <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="5.0.9"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> </PackageReference> <!-- SqlServer提供器 --> <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.9" /> <!-- CLI工具 --> <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="5.0.9"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> </PackageReference> </ItemGroup>
如果有其他依赖包间接引用了EF Core 5.0.8,用dotnet list package --include-transitive命令找出这些包,然后手动指定它们的版本或者添加版本覆盖规则。
2. 清理缓存与构建文件,重新恢复依赖
版本冲突经常和缓存有关,按顺序执行以下操作:
- 清理NuGet本地缓存:
dotnet nuget locals all --clear - 删除项目根目录下的
bin和obj文件夹 - 重新恢复依赖:
dotnet restore
3. 匹配.NET SDK与Runtime版本
EF Core 5.0.9对应的.NET 5 SDK版本是5.0.402,先确认本地安装的版本:
dotnet --list-sdks
如果没有这个版本,去下载安装对应的SDK。同时可以在项目文件里强制指定Runtime版本,避免自动匹配旧版本:
<PropertyGroup> <TargetFramework>net5.0</TargetFramework> <RuntimeFrameworkVersion>5.0.9</RuntimeFrameworkVersion> <RollForward>LatestMinor</RollForward> </PropertyGroup>
4. 升级EF Core CLI工具到对应版本
脚手架生成依赖全局的dotnet-ef工具,如果工具版本和项目版本不匹配,就会导致降级。先卸载旧版本,再安装5.0.9版本:
# 卸载旧版本 dotnet tool uninstall --global dotnet-ef # 安装对应版本 dotnet tool install --global dotnet-ef --version 5.0.9
5. 添加程序集绑定重定向(兜底方案)
如果前面的步骤都做完了还是有加载错误,就在web.config(Web项目)里添加绑定重定向,强制使用5.0.9版本:
<configuration> <!-- 其他配置 --> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="Microsoft.EntityFrameworkCore.SqlServer" publicKeyToken="adb9793829ddae60" culture="neutral" /> <bindingRedirect oldVersion="0.0.0.0-5.0.9.0" newVersion="5.0.9.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="Microsoft.EntityFrameworkCore" publicKeyToken="adb9793829ddae60" culture="neutral" /> <bindingRedirect oldVersion="0.0.0.0-5.0.9.0" newVersion="5.0.9.0" /> </dependentAssembly> </assemblyBinding> </runtime> </configuration>
6. 重新生成脚手架
完成以上步骤后,再尝试生成Razor页面脚手架。如果还是出现降级,手动修改生成后的代码里的包引用为5.0.9,然后再次执行dotnet restore和dotnet build。
至于你遇到的object reference not set to an instance of an object错误,大概率是因为EF上下文初始化时,程序集版本不匹配导致依赖加载失败,只要解决了版本统一问题,这个空引用错误应该会自动消失。
内容的提问来源于stack exchange,提问作者MatejKr

