I have 2 models and want to create a foreign key relationship. Basically each note should be assigned to a user.
[Table("UserProfile")]
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
}
[Table("UserNotes")]
public class UserNotes
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int NoteId { get; set; }
[ForeignKey("UserProfile")]
public virtual int UserId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public string Added { get; set; }
public DateTime? Edited { get; set; }
}
When I attempt to add new user note I get: The ForeignKeyAttribute on property 'UserId' on type 'note.DO.Models.UserNotes' is not valid. The navigation property 'UserProfile' was not found on the dependent type 'note.DO.Models.UserNotes'. The Name value should be a valid navigation property name.
I have tried a lot of combinations including those found in similar questions but none of them worked.
Try this :
public virtual int UserId { get; set; }
[ForeignKey("UserId")]
public virtual UserProfile User { get; set; }
This way, you pair foreign key property with navigation property.
Edit : you can also write it like this :
[ForeignKey("UserProfile")]
public virtual int UserId { get; set; }
public virtual UserProfile UserProfile { get; set; }
Those two snippets gives the same result. Your error message says that "UserProfile" property is missing, you just have to add it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With