MongoDb一对多映射

丹尼

我试图与MongoDb建立一对多的关系,但坚持加入这两个系列。我在下面做了一个例子,看看我现在是如何做的。

// schools collection
{
  _id: ObjectId("5ef206d1d21c573718ae6eda")
  name: "Hogwarts School of Witchcraft and Wizardry"
}

// students collection
{
  _id: ObjectId("5efed5df8b28770c2cb344b9"),
  school_id: ObjectId("5ef206d1d21c573718ae6eda")
  firstName: "Harry"
  lastName: "Potter"
}

.net项目中的模型类:

public class School
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; }
    
    public string Name { get; set; }
    public List<Student> Students { get; set; }
}

public class Student
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; }
    
    [BsonRepresentation(BsonType.ObjectId)]
    [Required]
    public string School_id { get; set; }
    
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

如何将映射studentsschool对象中?我尝试了这些代码,但没有一个起作用。

// 1st attempt
var q = _schools.Aggregate().Lookup<School, Student, School>(_students, school => school.Id, student 
=> student.school_id, a => a.Students);

// 2nd attempt
var q = from school in _schools.AsQueryable()
        join student in _students.AsQueryable() on school.Id equals student.school_id into students
        select new School()
        {
            Students = students
        };

var result = q.ToList();

我想念什么?

丹尼

实际上,两个代码段都是有效的,唯一的错误是,我school_id在数据库中拼写了错误的值,并引用了一个不存在的School文档。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章