即使我定义共享主键和外键,1 对 1 关系也不起作用
我正在尝试在两个类之间建立 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论