You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Entity Framework Code-First生成错误外键的问题排查求助

问题原因

问题出在ParimutuelEntry类中的List<Bet> Bets导航属性——EF Core会自动根据导航属性推断实体间的关系。因为你在ParimutuelEntry里声明了一个Bet的集合,EF默认会认为ParimutuelEntry和Bet之间存在一对多关系,所以自动在Bet表中生成了ParimutuelEntryId外键字段,这完全不符合你通过BetSelection关联两者的设计。

解决方案

1. 移除错误的导航属性

直接删除ParimutuelEntry中的List<Bet> Bets属性:

public class ParimutuelEntry
{
    public int Id { get; set; }
    public int ParimutuelEventId { get; set; }
    public string Description { get; set; } = null!;
    public int? Position { get; set; } = null;
    public bool Scratched { get; set; }
    // 移除错误的导航属性
    // public List<Bet> Bets { get; set; } = null!;
}

2. 完善BetSelection的关联配置

为了确保EF Core正确识别BetSelection作为Bet和ParimutuelEntry的中间关联表,需要给BetSelection添加对应的导航属性并配置外键:

public class BetSelection
{
    public int Id { get; set; }
    [ForeignKey(nameof(Bet))]
    public int BetId { get; set; }
    public Bet Bet { get; set; } = null!;
    
    [ForeignKey(nameof(ParimutuelEntry))]
    public int ParimutuelEntryId { get; set; }
    public ParimutuelEntry ParimutuelEntry { get; set; } = null!;
}

如果需要从ParimutuelEntry反向查询关联的投注选项,可以在ParimutuelEntry中添加BetSelection的集合:

public class ParimutuelEntry
{
    // ... 其他属性
    public List<BetSelection> BetSelections { get; set; } = null!;
}

3. (可选)用Fluent API明确配置关系

如果更倾向于用Fluent API控制实体关系(配置更清晰),可以在你的DbContext的OnModelCreating方法中添加以下配置:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    // 配置Bet与BetSelection的一对多关系
    modelBuilder.Entity<Bet>()
        .HasMany(b => b.BetSelections)
        .WithOne(bs => bs.Bet)
        .HasForeignKey(bs => bs.BetId)
        .OnDelete(DeleteBehavior.Cascade); // 根据业务需求选择删除行为

    // 配置ParimutuelEntry与BetSelection的一对多关系
    modelBuilder.Entity<ParimutuelEntry>()
        .HasMany(pe => pe.BetSelections)
        .WithOne(bs => bs.ParimutuelEntry)
        .HasForeignKey(bs => bs.ParimutuelEntryId)
        .OnDelete(DeleteBehavior.Restrict); // 根据业务需求选择删除行为
}

内容的提问来源于stack exchange,提问作者Argle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 23:50:28