5

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.

1
  • Does this have anything to do with asp.net? Commented Dec 17, 2014 at 7:06

1 Answer 1

17

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Why do we need to use the virtual keyword when declaring foreign keys? Any chance you could answer that?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.