我有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; }
}
类实体
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());
}
}
初始化器
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;
}
}
我想知道如何将一个对象添加到另一个对象的集合中,然后还可以使用该集合中的内容来检索该对象
答案 0 :(得分:1)
我认为您正在寻找.Include()。 loading related entities有几种不同的策略。
using (var context = new DatabaseContext())
{
// Load all students and related classes
var classes1 = context.Classes
.Include(s => s.Students)
.ToList();
// Load one student and its related classes
var classt1 = context.Classes
.Where(s => s.Name == "someClassName")
.Include(s => s.Students)
.FirstOrDefault();
// Load all students and related classes
// using a string to specify the relationship
var classes2 = context.Classes
.Include("Students")
.ToList();
// Load one student and its related classes
// using a string to specify the relationship
var class2 = context.Classes
.Where(s => s.Name == "someName")
.Include("Students")
.FirstOrDefault();
}