实体类型要求定义主键

时间:2019-12-22 13:49:03

标签: c# asp.net asp.net-mvc entity-framework asp.net-core

我有3个模型类(Customer, Manager, Technician),它们从基类Person继承。 Id键在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()
    {
    }
}

2 个答案:

答案 0 :(得分:4)

您的代码示例中的问题是您应该在Id属性中添加 set ,以便Entity Framework可以 set 自动生成ID。

答案 1 :(得分:2)

我认为您的id财产需要有一个塞特犬

public int Id { get; }              // not work
public int Id { get; set; }         // work
public int Id { get; private set; } // also work

您可以更改课程Person

public class Person
{
    [Key]
    public int Id { get; private set; }
    [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()
    {

    }
}