Entity Framework returns ICollection<> with no values

573 views c#
7

I have 2 entities in a Many-To-Many relationship and I'd like to add a student to a class, but after I receive the class object from a query it shows that the property is empty. I've seen lots of similar problems but no answer really helped me in this case.

Here are my classes:

Student Entity

class Student
{
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
    public virtual string Surname { get; set; }

    public Student()
    {
        Classes = new HashSet<Class>();
    }

    public virtual ICollection<Class> Classes { get; set; }
}

Class Entity

class Class
{
    public virtual int Id { get; set; }
    public virtual string ClassName { get; set; }

    public Class()
    {
        Students = new HashSet<Student>();
    }

    public virtual ICollection<Student> Students { get; set; }
}

Context

class DatabaseContext : DbContext
{
    public DbSet<Student> Students { get; set; }
    public DbSet<Class> Classes { get; set; }

    public DatabaseContext()
    {
        Database.SetInitializer<DatabaseContext>(new Initializer());
    }
}

Initializer

class Initializer : DropCreateDatabaseAlways<DatabaseContext>
{
    protected override void Seed(DatabaseContext context)
    {
        Student student1 = new Student { Id = 1, Name = "Name", Surname = "Surname" };

        Class class1 = new Class { Id = 1, ClassName = "Math"};
        class1.Students.Add(student1); // The Count of the collection is 1

        context.Students.Add(student1);
        context.Class.Add(class1);

        base.Seed(context);
    }
}

Now when I try and receive the object through a method, the Count of the collection is 0

public static Class GetClass(int classId)
    {
        using (var context = new DatabaseContext())
        {
            Class receivedClass = context.Classes.Find(classId); // The collection is empty, the ClassName is there, though

            return receivedClass;
        }
    }

I'd like to know how can I add an object to a Collection of another object and then be able to also retrieve the object with the contents in the Collection

answered question

1 Answer

6

i feel your written code is right !! try using a true or false context.. Your Class is not well characterized also

posted this

Have an answer?

JD

Please login first before posting an answer.