所以我在我的 ASP.NET Core MVC 项目中有这个源生成器,它可以生成如下视图模型:
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using System.Text;
namespace SourceGenerator
{
[Generator]
public partial class ModelListGenerator : ISourceGenerator
{
public void Initialize(GeneratorInitializationContext context)
{
context.RegisterForSyntaxNotifications(() => new CustomSyntaxReceiver());
}
public void Execute(GeneratorExecutionContext context)
{
if (!(context.SyntaxReceiver is CustomSyntaxReceiver syntaxReceiver)) return;
foreach (var classDeclarationSyntax in syntaxReceiver.ClassDeclarationSyntaxes)
{
//var className = classDeclarationSyntax.Identifier.Text;
}
string projectName = "Boilerplate";
string className = "Person";
string code = @$"
using {projectName}.Domain;
using {projectName}.Models;
using System.Collections.Generic;
namespace {projectName}.Areas.AdminPortal.Models
{{
public class {className}ListModel
{{
public {className}ListModel()
{{
}}
public {className}ListModel(List<{className}> {className.ToLower()}s)
{{
foreach (var {className.ToLower()} in {className.ToLower()}s)
{{
{className}s.Add(new {className}Model({className.ToLower()}));
}}
}}
public List<{className}Model> {className}s {{ get; set; }} = new List<{className}Model>();
}}
}}
";
context.AddSource("ModelList.cs", SourceText.From(code, Encoding.UTF8));
}
}
}
源生成器工作出色。但是,当我尝试加载使用生成模型的视图时,我收到此错误:
InvalidOperationException:传递到 ViewDataDictionary 的模型项的类型为“Boilerplate.Areas.AdminPortal.Models.PersonListModel”,但此 ViewDataDictionary 实例需要“Boilerplate.Areas.AdminPortal.Models.PersonListModel”类型的模型项。
换句话说,它是在说“我想要一个 PersonListModel,但你给了我一个 PersonListModel”(LOL)。如果我在应用程序在调试模式下运行时更改Boilerplate.Areas.AdminPortal.Models.PersonListModel
为简单PersonListModel
,这会暂时修复它。但在某些时候,它会再次显示此错误。然后,如果我将代码从PersonListModel
回更改为Boilerplate.Areas.AdminPortal.Models.PersonListModel
(原始代码),它会再次工作一段时间。
显然,在 Razor 视图引擎难以识别传递给 ViewDataDictionary 的模型项是正确的位置时存在某种脱节。这是一个已知的错误?有解决方法还是我只是运气不好?谢谢!