Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting up foreign key in ASP.NET MVC 4

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.

like image 262
Paweł Duda Avatar asked Oct 22 '13 12:10

Paweł Duda


1 Answers

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.

like image 55
Réda Mattar Avatar answered Oct 28 '22 19:10

Réda Mattar