.NET 4.7.2 WebForms迁移EF Core 3.1时查询含不存在字段AttendeeId
解决EF Core生成SQL时添加不存在字段
AttendeeId的问题 问题原因
EF Core的约定优先配置机制在推断实体间关系时,因你定义了EventAttendee导航属性但未明确指定对应外键字段,导致EF错误推断出额外的外键字段AttendeeId(推测EventAttendee实体的主键名为AttendeeId,EF默认尝试用该主键名作为外键字段名,与你手动定义的EventAttendeeId产生冲突)。
解决方案
方案1:使用DataAnnotation特性明确外键
在EventAttendee导航属性上添加[ForeignKey]特性,指定对应外键字段为EventAttendeeId:
[Table("EntryAttendee")] public class EntryAttendee { // ... 其他属性省略 #region Relational Objects [ForeignKey("EventAttendeeId")] public virtual EventAttendee EventAttendee { get; set; } #endregion // ... 构造函数省略 }
方案2:使用Fluent API在DbContext中配置关系
在DbContext类的OnModelCreating方法中,手动配置EntryAttendee与EventAttendee的关联关系,明确指定外键:
protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<EntryAttendee>() .HasOne(ea => ea.EventAttendee) .WithMany() // 若EventAttendee无反向导航属性,直接使用WithMany() .HasForeignKey(ea => ea.EventAttendeeId); }
验证
修改后重新运行查询,EF Core生成的SQL将不再包含不存在的AttendeeId字段,仅使用你定义的EventAttendeeId作为外键进行关联查询。
内容的提问来源于stack exchange,提问作者JeffR
相关产品推荐
相关产品推荐

