Blood
Blood

Reputation: 4196

Entity Framework one-to-many relation

I have two simple classes:

class Student
{
    public int StudentId { get; set; }
    public int IndeksNo { get; set; }
    public string Name { get; set; }
    public string LastName { get; set; }
    public virtual Group Group { get; set; }
}

And

class Group
{
    public int GroupId { get; set; }
    public string Name { get; set; }
    public virtual List <Student > Students { get; set; }
}

Database is created correctly (using Code First). I have added couple items to both tables, but all the time Students list and Group property in Student are null. I have no idea why. I have searched solution for about an hour and i came up with something like this:

modelBuilder.Entity<Student>()
    .HasRequired(st => st.Group)
    .WithMany(gr => gr.Students)
    .WillCascadeOnDelete(false);

But it doesn't help. I have no idea what may went wrong or why Group.Students and Student.Group are always null. List of groups and list of students are selected from db successfully - i mean all params except those connections.

Upvotes: 2

Views: 62

Answers (1)

Alexandre Rondeau
Alexandre Rondeau

Reputation: 2687

In order to use the Lazy Loading feature of EntityFramework. Your navigation property must be virtual. In your Student class in the the case. The problem is with your Group class. The navigational property is a virtual List<Student> it must be a virtual ICollection<Student>

You can simply change your Group to

class Group
{
    public int GroupId { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Student > Students { get; set; }
}

Upvotes: 2

Related Questions