EF Core配置同实体双向关联中间表时迁移报错求助
EF Core 迁移报错:无法生成 NullabilityInfoContext 类型的 C# 字面量
问题场景
使用EF Core构建漫画相关数据表,需创建两个关联Manga实体的中间表:
MangaRelation:记录漫画间关联关系(续作、共享角色等)MangaRecommendation:记录漫画推荐关系
实体类定义
MangaRelation
public class MangaRelation : BaseEntity { public int ParentId { get; set; } public int ChildId { get; set; } public virtual Manga? Parent { get; set; } public virtual Manga? Child { get; set; } public RelationType RelationType { get; set; } public string? Description { get; set; } }
MangaRecommendation
public class MangaRecommendation : BaseEntity { public int MangaId { get; set; } public int RecommendedMangaId { get; set; } public virtual Manga? Manga { get; set; } public virtual Manga? RecommendedManga { get; set; } public string? Reason { get; set; } }
Manga
public partial class Manga : BaseEntity { public int MangaId { get; set; } public virtual ICollection<MangaRelation> Relations { get; set; } = new HashSet<MangaRelation>(); public virtual ICollection<MangaRecommendation> Recommendations { get; set; } = new HashSet<MangaRecommendation>(); }
DbContext 配置代码
protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); RegisterDbFunctions(modelBuilder); modelBuilder.Entity<Manga>(e => { e.HasKey(p => p.MangaId); e.HasMany(p => p.RelationShips).WithOne(m => m.Parent).OnDelete(DeleteBehavior.Cascade); e.HasMany(p => p.Recommendations).WithOne(m => m.Manga).OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity<MangaRelation>(e => { e.HasKey(k => new { k.MangaParentId, k.MangaChildId }); e.HasIndex(p => p.MangaParentId); e.HasIndex(p => p.MangaChildId); e.Property(p => p.MangaParentId); e.Property(p => p.MangaChildId); e.HasOne(p => p.Parent).WithMany().HasForeignKey(k => k.MangaParentId).HasConstraintName("FK_Manga_Parent") .OnDelete(DeleteBehavior.NoAction); e.HasOne(p => p.Child).WithMany().HasForeignKey(k => k.MangaChildId).HasConstraintName("FK_Manga_Child") .OnDelete(DeleteBehavior.NoAction); e.Property(p => p.RelationType).HasConversion<int>(); e.Property(p => p.Description); }); modelBuilder.Entity<MangaRecommondation>(e => { e.HasKey(k => new { k.MangaId, k.RecommendedMangaId }); e.HasIndex(p => p.MangaId); e.HasIndex(p => p.RecommendedMangaId); e.Property(p => p.Reason); e.Property(p => p.MangaId); e.HasOne(p => p.Manga).WithMany().HasForeignKey(k => k.MangaId).HasConstraintName("FK_MangaParent_Rec") .OnDelete(DeleteBehavior.NoAction); e.HasOne(p => p.RecommendedManga).WithMany().HasForeignKey(k => k.RecommendedMangaId) .HasConstraintName("FK_MangaRecParent_Rec").OnDelete(DeleteBehavior.NoAction); e.Property(p => p.RecommendedMangaId); }); }
报错信息
启用Nullable Context后,执行EF Core迁移命令时抛出以下错误:
System.InvalidOperationException: Cannot scaffold C# literals of type 'System.Reflection.NullabilityInfoContext'. The provider should implement CoreTypeMapping.GenerateCodeLiteral to support using it at design time. at Microsoft.EntityFrameworkCore.Design.Internal.CSharpHelper.UnknownLiteral(Object value) at Microsoft.EntityFrameworkCore.Design.Internal.CSharpHelper.<Fragment>g__AppendMethodCall|52_0(IMethodCallCodeFragment current, <>c__DisplayClass52_0&) at Microsoft.EntityFrameworkCore.Design.Internal.CSharpHelper.Fragment(IMethodCallCodeFragment fragment, Int32 indent) at Microsoft.EntityFrameworkCore.Migrations.Design.CSharpSnapshotGenerator.GenerateAnnotations(String builderName, IAnnotatable annotatable, IndentedStringBuilder stringBuilder, Dictionary`2 annotations, Boolean inChainedCall, Boolean leadingNewline) at Microsoft.EntityFrameworkCore.Migrations.Design.CSharpSnapshotGenerator.Generate(String modelBuilderName, IModel model, IndentedStringBuilder stringBuilder) at Microsoft.EntityFrameworkCore.Migrations.Design.CSharpMigrationsGenerator.GenerateMetadata(String migrationNamespace, Type contextType, String migrationName, String migrationId, IModel targetModel) at Microsoft.EntityFrameworkCore.Migrations.Design.MigrationsScaffolder.ScaffoldMigration(String migrationName, String rootNamespace, String subNamespace, String language) at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType, String namespace) at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType, String namespace) at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigration.<>c__DisplayClass0_0.<.ctor>b__0() at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0() at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action) Cannot scaffold C# literals of type 'System.Reflection.NullabilityInfoContext'. The provider should implement CoreTypeMapping.GenerateCodeLiteral to support using it at design time.
解决方案
1. 修正实体与配置的字段/名称不匹配问题
代码中存在多处不一致,这是引发关系配置错误的核心原因:
MangaRelation实体定义的是ParentId/ChildId,但配置中使用MangaParentId/MangaChildId,需统一字段名(要么修改实体,要么修改配置)Manga实体的集合属性是Relations,但配置中写的是p.RelationShips,需修正为p.Relations- 配置中写错实体名:
MangaRecommondation应为MangaRecommendation
修正后的核心配置片段:
// Manga实体配置修正 modelBuilder.Entity<Manga>(e => { e.HasKey(p => p.MangaId); e.HasMany(p => p.Relations).WithOne(m => m.Parent).OnDelete(DeleteBehavior.Cascade); e.HasMany(p => p.Recommendations).WithOne(m => m.Manga).OnDelete(DeleteBehavior.Cascade); }); // MangaRecommendation实体配置修正 modelBuilder.Entity<MangaRecommendation>(e => { e.HasKey(k => new { k.MangaId, k.RecommendedMangaId }); e.HasIndex(p => p.MangaId); e.HasIndex(p => p.RecommendedMangaId); e.Property(p => p.Reason); e.HasOne(p => p.Manga).WithMany(m => m.Recommendations).HasForeignKey(k => k.MangaId) .HasConstraintName("FK_MangaParent_Rec").OnDelete(DeleteBehavior.NoAction); e.HasOne(p => p.RecommendedManga).WithMany().HasForeignKey(k => k.RecommendedMangaId) .HasConstraintName("FK_MangaRecParent_Rec").OnDelete(DeleteBehavior.NoAction); });
2. 处理Nullable Context相关bug
如果字段修正后仍报错,尝试以下操作:
- 升级EF Core版本至6.0.7及以上,旧版本在Nullable Context下存在设计时生成的bug
- 临时关闭项目Nullable Context(修改项目文件中的
<Nullable>enable</Nullable>为<Nullable>disable</Nullable>),生成迁移后再重新开启 - 检查
BaseEntity的配置,避免将NullabilityInfoContext相关内容注入到模型注解中
3. 清理迁移缓存
执行以下命令清理设计时缓存,再重新生成迁移:
dotnet ef migrations remove dotnet clean dotnet restore dotnet ef migrations add InitialCreate
内容的提问来源于stack exchange,提问作者Pascal Klose
相关产品推荐
相关产品推荐

