ASP.NET Core Razor Pages项目CS0229歧义错误原因咨询
Great question—let's dig into why you're seeing those frustrating ambiguity errors and how to fix them.
The Core Issue: Namespace Collision
The problem boils down to duplicate class names in the same namespace. When you used the scaffolding tool to generate CRUD pages for both your Movie and Review models, it dumped all the generated page models (like CreateModel, IndexModel, EditModel) into the root RazorPagesMovie namespace instead of nesting them under their respective subfolder namespaces (RazorPagesMovie.Pages.Movies and RazorPagesMovie.Pages.Reviews).
In C#, if two classes have the exact same name and live in the same namespace, the compiler has no way to tell them apart. That's why you're seeing errors like Ambiguity between 'CreateModel._context' and 'CreateModel._context'—it's confused between the CreateModel from your Movies pages and the one from your Reviews pages.
Why Did the Scaffolder Do This?
By default, the ASP.NET Core scaffolding tool uses your project's root namespace for all generated code unless you explicitly tell it otherwise. It doesn't automatically infer the namespace from the folder structure where you're creating the pages, which leads to this collision when you add multiple CRUD sets in separate subfolders.
How to Fix It
You've got two solid options to resolve this:
Retroactively Fix Namespaces
- Go through each
.cshtml.csfile in thePages/Moviesfolder and change the namespace fromRazorPagesMovietoRazorPagesMovie.Pages.Movies - Repeat this for every
.cshtml.csfile inPages/Reviews, updating the namespace toRazorPagesMovie.Pages.Reviews - Don't forget to update the
@modeldirective in each corresponding.cshtmlfile to match the new fully qualified namespace (e.g.,@model RazorPagesMovie.Pages.Reviews.CreateModel)
- Go through each
Configure Scaffolding Correctly for Future Generations
- Next time you run the scaffolding wizard, look for the "Namespace" option (usually tucked in the advanced settings) and set it to the sub-namespace corresponding to your target folder (like
RazorPagesMovie.Pages.Reviews). This ensures the scaffolder generates code with the correct namespace right out the gate, avoiding collisions entirely.
- Next time you run the scaffolding wizard, look for the "Namespace" option (usually tucked in the advanced settings) and set it to the sub-namespace corresponding to your target folder (like
Once you adjust those namespaces, the compiler will be able to tell your CreateModel (and other page model) classes apart, and those ambiguity errors should vanish.
内容的提问来源于stack exchange,提问作者Efthymios Kalyviotis

