Pete
Pete

Reputation: 58462

MVC Model Foreign Key Navigational Property

I currently have a blog model in which I have a foreign key to the blog author:

    [Required]
    [ForeignKey("BlogAuthorModel")]
    [Display(Name = "Author")]
    public int BlogAuthorId { get; set; }

    public BlogAuthorModel BlogAuthorModel { get; set; }

I have had to add the BlogAuthorModel property to the class in order for me to make the foreign key work.

Does anyone know what this is for as when I try to use it, it is null - should it auto complete or do I have to put my own code in to make it use the foreign key to populate?

Update

Whoever marked this as a duplicate, my question wasn't about how to add foreign keys, it was how to populate the BlogAuthorModel, it turns out if you make it virtual then it will auto populate:

    public virtual BlogAuthorModel BlogAuthorModel { get; set; }

Upvotes: 0

Views: 1380

Answers (1)

DeeDub
DeeDub

Reputation: 1662

That is for the navigational property of your class for EF. I believe you need to move the ForiegnKey down to the actual object, pointing to the foreign key field within your respective class.

[Required]
[Display(Name = "Author")]
public int BlogAuthorId { get; set; }

[ForeignKey("BlogAuthorId")]
public BlogAuthorModel BlogAuthorModel { get; set; }

Upvotes: 1

Related Questions