i_ll_be_back i_ll_be_back - 3 months ago 11
C# Question

Error with primary key in one-to-one relationship using Entity Framework

I've 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 connect them by having both as primary key the
UsrID
and I get an error that
UsrDetails
don't have a primary key because I'm using the foreign key attribute. Any ideas?

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 entities must have a PK property. In this case where you are representing a one to one relationship, the PK of the dependent entity also is the FK. You can check this tutorial in case you need more info.

Comments