Reputation: 585
I have linked my members table with Application user by foreign key as can be found in the Model
public int MemberId { get; set; }
public int? UserId { get; set; }
[ForeignKey("UserId")]
public ApplicationUser User { get; set; }
In Razor View I want to be able to retrieve User details eg
@Model.User.FirstName
But I get
System.NullReferenceException: Object reference not set to an instance of an object.
Not sure what is missing
Upvotes: 0
Views: 705
Reputation: 5748
You must make your UserId->User relation virtual. So:
public int? UserId { get; set; }
[ForeignKey("UserId")]
public virtual ApplicationUser User { get; set; }
Adding the virtual
keyword to the declaration of User
means it will be "Lazy Loaded" which in really short terms means that as soon as you refer to the User
object, it loads the data from the database.
For more information, see https://msdn.microsoft.com/en-us/library/jj574232(v=vs.113).aspx#Anchor_1
Upvotes: 2