首页 > 解决方案 > 实体类型需要定义主键

问题描述

我有 3 个模型类 ( Customer, Manager, Technician) 从基类继承PersonId键在基类中定义Person

当我尝试为Customer该类生成控制器时,会显示一个错误,指示实体类型客户必须具有主键。

这是我的Person课:

public class Person
{
    [Key]
    public int Id { get; }
    [EmailAddress]
    public string? Email { get; set; }
    public int? Cin { get; set; }
    public string? Address { get; set; }
    [Required]
    public string Name { get; set; }
    [Phone, Required]
    public int PhoneNumber { get; set; }

    public Person(int PhoneNumber, string Name, string Email = null, int? Cin = null, string Address = null)
    {
        this.PhoneNumber = PhoneNumber;
        this.Name = Name;
        this.Email = Email;
        this.Address = Address;
        this.Cin = Cin;
    }

    public Person()
    {
    }
}

这是我的Customer课:

public class Customer : Person
{
    public List<Device> CustomerDevices { get; set; }

    public Customer(int PhoneNumber, string Name, string Email = null, int? Cin = null, string Address = null)
        : base(PhoneNumber, Name, Email, Cin, Address)
    {
    }

    public Customer() : base()
    {
    }
}

标签: c#asp.netasp.net-mvcentity-frameworkasp.net-core

解决方案


您的代码示例中的问题是您应该将set添加到您的Id属性中,以便实体框架可以设置自动生成的 id。


推荐阅读