簡體   English   中英

實體類型需要定義一個主鍵

[英]Entity Type requires a primary key to be defined

我有 3 個從基類Person繼承的模型類( Customer, Manager, Technician )。 Id鍵在Person基類中定義。

當我嘗試為Customer類生成控制器時,會出現一個錯誤,表明實體類型 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()
    {
    }
}

您的代碼示例中的問題是您應該將set添加到您的Id屬性,以便實體框架可以設置自動生成的 id。

我認為你的id屬性需要有一個 setter

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()
    {

    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM