.NET 7 WinForms执行add-migration时遇Font实体构造器错误求助
问题重现
在.NET 7 Windows Forms项目中执行Add-Migration命令时出现错误,相关截图如下:



项目中的ApplicationDbContext代码如下:
namespace ManegmentSystemCompany.Data.Context { public class ApplicationDbContext : DbContext { public DbSet<Catogry> Catogry { get; set; } public DbSet<Custemer> Custemer { get; set; } public DbSet<Employee> employees { get; set; } public DbSet<Pruducts> pruducts { get; set; } public DbSet<Stores> stores { get; set; } public DbSet<Supplier> suppliers { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer("Data Source=.;Initial Catalog=WhereHouseDb; Integrated Security=true"); } } }
执行Add-Migration后弹出的错误信息:
找不到适用于实体类型'Font'的合适构造器。以下构造器的参数无法绑定到实体类型的属性:
无法绑定'Font(SerializationInfo info, StreamingContext context)'中的'info'、'context'
无法绑定'Font(Font prototype, FontStyle newStyle)'中的'prototype'、'newStyle'
无法绑定'Font(FontFamily family, float emSize, FontStyle style, GraphicsUnit unit)'中的'family'、'emSize'、'style'、'unit'
无法绑定'Font(FontFamily family, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet)'中的'family'、'emSize'、'style'、'unit'、'gdiCharSet'
无法绑定'Font(FontFamily family, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet, bool gdiVerticalFont)'中的'family'、'emSize'、'style'、'unit'、'gdiCharSet'、'gdiVerticalFont'
无法绑定'Font(string familyName, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet)'中的'familyName'、'emSize'、'style'、'unit'、'gdiCharSet'
无法绑定'Font(string familyName, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet, bool gdiVerticalFont)'中的'familyName'、'emSize'、'style'、'unit'、'gdiCharSet'、'gdiVerticalFont'
无法绑定'Font(FontFamily family, float emSize, FontStyle style)'中的'family'、'emSize'、'style'
无法绑定'Font(FontFamily family, float emSize, GraphicsUnit unit)'中的'family'、'emSize'、'unit'
无法绑定'Font(FontFamily family, float emSize)'中的'family'、'emSize'
无法绑定'Font(string familyName, float emSize, FontStyle style, GraphicsUnit unit)'中的'familyName'、'emSize'、'style'、'unit'
解决方案
这个错误的核心原因是EF Core把WinForms的Font类型误识别为需要映射到数据库的实体类,通常是你的业务实体(比如Employee、Pruducts等)中直接定义了Font类型的属性,而EF Core无法处理这种非业务数据类型的映射。
解决方法有两种:
- 移除实体类中的Font属性:实体类只应该存储业务相关的数据,WinForms的UI样式(比如字体)属于界面层逻辑,应该放在窗体或控件的代码中,不要和实体模型混合。
- 标记Font属性为不映射:如果确实需要保留该属性(不推荐),可以给
Font属性添加[NotMapped]特性,告诉EF Core跳过该属性的数据库映射:
using System.ComponentModel.DataAnnotations.Schema; public class Employee { // 其他业务属性... public int Id { get; set; } public string Name { get; set; } // 添加NotMapped特性,避免EF Core尝试映射该属性 [NotMapped] public Font DisplayFont { get; set; } }
修改完成后,重新执行Add-Migration命令即可正常生成迁移文件。
内容的提问来源于stack exchange,提问作者karam williame

