即使我定义共享主键和外键,1 对 1 关系也不起作用

发布于 2025-01-11 07:15:44 字数 1299 浏览 0 评论 0原文

我正在尝试在两个类之间建立 1 对 1 的关系:

public class Player
{
    [Key]
    public int PlayerId { get; set; }
    public string PlayerName { get; set; }
    public int PlayerRating { get; set; }
    public int PlayerSkill { get; set; }
    public virtual Record Record { get; set; }
}

public class Record
{
    [Key]
    [ForeignKey("Player")]
    public int RecordId { get; set; }
    public List<Player> RecordWins { get; set; }
    public List<Player> RecordLosses { get; set; }
    public virtual Player Player { get; set; }
}

public class DataContext : DbContext
{
    public DbSet<Player> Players { get; set; }
    public DbSet<Record> Records { get; set; }

    public DataContext(DbContextOptions<DataContext> options) : base(options)
    {

    }
}

根据此 文章,我必须在 Player.cs 上定义一个主键,在 Record.cs 上定义一个主键和外键(我就是这样做的)。

当我使用以下命令迁移此更改时:

Add-migration AddPlayerRecordRelationship

它不起作用。它说:

无法确定“Record”类型的导航“Player.Record”表示的关系。手动配置关系,或者使用“[NotMapped]”属性或使用“EntityTypeBuilder”忽略此属性。在“OnModelCreating”中忽略“。

使用这种方法有什么遗漏吗?我将不胜感激任何帮助。谢谢你!

I'm trying to set up a 1 to 1 relationship between two classes:

public class Player
{
    [Key]
    public int PlayerId { get; set; }
    public string PlayerName { get; set; }
    public int PlayerRating { get; set; }
    public int PlayerSkill { get; set; }
    public virtual Record Record { get; set; }
}

public class Record
{
    [Key]
    [ForeignKey("Player")]
    public int RecordId { get; set; }
    public List<Player> RecordWins { get; set; }
    public List<Player> RecordLosses { get; set; }
    public virtual Player Player { get; set; }
}

public class DataContext : DbContext
{
    public DbSet<Player> Players { get; set; }
    public DbSet<Record> Records { get; set; }

    public DataContext(DbContextOptions<DataContext> options) : base(options)
    {

    }
}

According to this article, I must define a primary key on Player.cs and a primary and foreign key on Record.cs (which I did).

When I migrate this change using:

Add-migration AddPlayerRecordRelationship

It didn't work. It says:

"Unable to determine the relationship represented by navigation 'Player.Record' of type 'Record'. Either manually configure the relationship, or ignore this property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'."

Is there anything I'm missing using this approach? I would appreciate any help. Thank you!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文