У меня есть 2 сущности в отношении «многие ко многим», и я хотел бы добавить ученика в класс, но после того, как я получил объект класса из запроса, он показывает, что свойство пусто. Я видел много подобных проблем, но в этом случае мне не помог ответ.
Вот мои занятия:
Студенческая организация
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; }
}
Класс 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; }
}
Контекст
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.Classes.Add(class1);
base.Seed(context);
}
}
Теперь, когда я пытаюсь получить объект с помощью метода, счетчик коллекции равен 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;
}
}
Я хотел бы знать, как я могу добавить объект в коллекцию другого объекта и затем иметь возможность также извлекать объект с содержимым в коллекции