我有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()
{
}
}
答案 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()
{
}
}