简体   繁体   中英

Entity Framework Core requires a primary key to be defined

I currently have 2 entities, Player and Role . I'm trying to create a migration (first migration) for these two entities.

Player.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:

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:

System.InvalidOperationException: The entity type 'Role' requires a primary key to be defined. If you intended to use a keyless entity type call 'HasNoKey()'

However, if I remove the Role entity and change Role of Player to an int, it works. So the Player entity is correct, while the Id property of both entities is exactly the same.

How come I still get an error for the Role entity?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM