Entity Framework null object
asp.net-mvc, c#, entity-framework
Solution
Either load navigation property `Restaurant` explicitly via `Include` method:
var review = _db.Reviews.Include(r => r.Restaurant).FindTheLatest(1).Single();
or you can enable lazy loading for that property, by making it virtual:
public virtual Restaurant Restaurant { get; set; }
You can read more about loading related entities here.
Problem
I have simple DBcontext class called OdeToFoodDb: ``` public class OdeToFoodDb: DbContext { public DbSet<Restaurant> Restaurants { get; set; } public DbSet<Review> Reviews { get; set; } protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder) { modelBuilder.Entity<Restaurant>() .HasMany(resturant => resturant.Reviews) .WithRequired(review => review.Resturant); base.OnModelCreating(modelBuilder); } } ``` and the class definition: ``` public class Restaurant { //public virtual int ID { get; set; } public virtual int RestaurantId { get; set; } public virtual string Name { get; set; } public virtual Address Address { get; set; } public virtual IList<Review> Reviews { get; set; } } public class Review : IValidatableObject { public int ReviewId { get; set; } [DisplayName("Digning Date")] [DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)] [DataType(DataType.Date)] public DateTime Created { get; set; } [Range(1, 10)] public int Rating { get; set; } [Required] [DataType(DataType.MultilineText)] public string Body { get; set; } public int RestaurantId { get; set; } public Restaurant Resturant { get; set; } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { var fields = new[]{ "Created"}; if(Created > DateTime.Now) { yield return new ValidationResult("Created date cannot be in the future.", fields); } if (Created < DateTime.Now.AddYears(-1)) { yield return new ValidationResult("Created date cannot be to far in the past.", fields); } } } ``` my problem is when i select a review from dbcontext like this: ``` OdeToFoodDb _db = new OdeToFoodDb(); public PartialViewResult LatestReview() { var review = _db.Reviews.FindTheLatest(1).Single(); //************************************ return PartialView("_Review", review); } ``` I checked that the review.Restaurant is null! while the other property have a value. What is wrong with my code?