[英]Entity Framework Core requires a primary key to be defined
I currently have 2 entities, Player
and Role
.我目前有 2 个实体,
Player
和Role
。 I'm trying to create a migration (first migration) for these two entities.我正在尝试为这两个实体创建迁移(第一次迁移)。
Player.cs:播放器.cs:
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Stargazer.Game.Roles;
namespace Stargazer.Game.Players
{
[Table("players")]
public class Player
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
[MaxLength(15)]
public string Username { get; set; }
[Required]
public string Password { get; set; }
[Required]
public string Email { get; set; }
public string Motto { get; set; }
[Required]
public string Figure { get; set; }
[Required]
public char Gender { get; set; }
[Required]
public Role Role { get; set; }
[Required]
[DefaultValue(500)]
public int Coins { get; set; }
public string? ConsoleMotto { get; set; }
[Required]
public string Salt { get; set; }
}
}
And Role.cs:和 Role.cs:
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Stargazer.Game.Roles
{
[Table("roles")]
public class Role
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; }
[Required]
public string Name { get; }
}
}
However, ONLY for Role
, I get this error:但是,仅对于
Role
,我收到此错误:
System.InvalidOperationException: The entity type 'Role' requires a primary key to be defined.
System.InvalidOperationException:实体类型“角色”需要定义主键。 If you intended to use a keyless entity type call 'HasNoKey()'
如果您打算使用无密钥实体类型调用“HasNoKey()”
However, if I remove the Role
entity and change Role
of Player
to an int, it works.但是,如果我删除
Role
实体并将Player
的Role
更改为 int,它就可以工作。 So the Player
entity is correct, while the Id property of both entities is exactly the same.所以
Player
实体是正确的,而两个实体的 Id 属性是完全一样的。
How come I still get an error for the Role
entity?为什么我仍然收到
Role
实体的错误?
Even though it was a stupid mistake, I still want to keep it here for future reference & in case somebody makes the same mistake..即使这是一个愚蠢的错误,我仍然想将其保留在这里以供将来参考,以防有人犯同样的错误。
I forgot to add setters on my properties.我忘了在我的属性上添加设置器。 I had to change my properties to this:
我不得不将我的属性更改为:
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
public string Name { get; set; }
And then it works.然后它就起作用了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.