Here is the model code:

public class Lection { [Key] public int LectionId { get; set; } public string Name { get; set; } public string SubText { get; set; } public ICollection<Chapter> Chapters { get; set; } public string OtherAutors { get; set; } public ICollection<Lecturer> Owners { get; set; } public ICollection<Link> Links { get; set; } public Lection() { Chapters = new List<Chapter>(); Owners = new List<Lecturer>(); Links = new List<Link>(); } } public class Chapter { [Key] public int ChapterId { get; set; } public string Name { get; set; } public string SubText { get; set; } public string Text { get; set; } public int LectionId { get; set; } [ForeignKey("LectionId")] public Lection Lection { get; set; } } 

This shows that the database is normally filled with test data. Screenshot

But while this code:

  @foreach (var c in ViewBag.Lection.Chapters) { <h2 class="ChapterTitle"><a name="@c.Name">@c.Name</a></h2> <div class="ChapterSub">@c.SubText</div> <p>@c.Text</p> } 

does not display anything. Well, the controller code just in case:

 if ((ViewBag.Lection = db.Lections.Find(id)) == null) return HttpNotFound(); return View(); 

Tell me who understands this, for there is simply no power.

    1 answer 1

    What would have worked navigational properties, they must be marked as virtual , because EF for the fact that the mechanism of navigation properties worked, overrides them.

     public class Lection { [Key] public int LectionId { get; set; } public string Name { get; set; } public string SubText { get; set; } public virtual ICollection<Chapter> Chapters { get; set; } public string OtherAutors { get; set; } public virtual ICollection<Lecturer> Owners { get; set; } public virtual ICollection<Link> Links { get; set; } public Lection() { Chapters = new List<Chapter>(); Owners = new List<Lecturer>(); Links = new List<Link>(); } } public class Chapter { [Key] public int ChapterId { get; set; } public string Name { get; set; } public string SubText { get; set; } public string Text { get; set; } public int LectionId { get; set; } [ForeignKey("LectionId")] public virtual Lection Lection { get; set; } } 
    • Lord ... Thank you so much) After Java, I don’t notice this virtual point, it’s even offensive how much time I killed because of inattention. - Uraty