Reputation: 25
I have 3 model classes (Customer, Manager, Technician
) that inherit from the base class Person
. The Id
key is defined in the Person
base class.
When I try to generate a controller for the Customer
class, an error shows up indicating that the entity type customer must have a primary key.
Here's my Person
class:
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()
{
}
}
And here's my Customer
class:
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()
{
}
}
Upvotes: 1
Views: 216
Reputation: 91
The problem in your code example is that you should add set to your Id
property, so Entity Framework can set autogenerated id.
Upvotes: 4
Reputation: 4319
I think your id
property needs to have a setter
public int Id { get; } // not work
public int Id { get; set; } // work
public int Id { get; private set; } // also work
you can change class 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()
{
}
}
Upvotes: 2