One-to-One Primary Key Error Using Entity Framework

I created a database according to which the user profile is formed by the following two classes:

public class Usr { [Key()] public int UsrID { get; set; } public virtual UsrType UsrType { get; set; } public virtual UsrStatus UsrStatus { get; set; } [Required] [MaxLength(100, ErrorMessage = "Email can only contain {0} characters")] public string UsrEmail { get; set; } [Required] [MaxLength(32, ErrorMessage = "Password can only contain {0} characters")] [MinLength(8, ErrorMessage = "Password must be at least {0} characters")] public string UsrPassword { get; set; } } public class UsrDetails { [ForeignKey("UsrID")] [Required] public virtual Usr Usr { get; set; } [Required] [MaxLength(40, ErrorMessage = "Name can only contain {0} characters")] public string UsrName { get; set; } [Required] [MaxLength(40, ErrorMessage = "Surname can only contain {0} characters")] public string UsrSurname { get; set; } [Required] [MaxLength(20, ErrorMessage = "Country can only contain {0} characters")] public string UsrCountry { get; set; } [Required] [MaxLength(20, ErrorMessage = "City can only contain {0} characters")] public string UsrCity { get; set; } [Required] [MaxLength(40, ErrorMessage = "Street can only contain {0} characters")] public string UsrStreet { get; set; } [Required] public int UsrNum { get; set; } [Required] public int UsrPostalCode { get; set; } } 

I want to bind them with both the UsrID primary key, and I get an error that UsrDetails does not have a primary key, because I use the foreign key attribute. Any ideas?

+5
source share
1 answer

You need to declare a key property in UserDetails with the same name that you declare in the ForeignKey attribute:

 public class UsrDetails { [Key] public int UsrID{ get; set; } [ForeignKey("UsrID")] public virtual Usr Usr { get; set; } } 

All your objects must have a PK property. In this case, when you represent a one-to-one relationship, the PK of the dependent object is also FK. You can check out this tutorial if you need more information.

+4
source

Source: https://habr.com/ru/post/1246963/


All Articles