Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
lookup one to many relationship
using MongoDB.Driver;
using MongoDB.Driver.Linq;
using MongoDB.Entities;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace TestApplication
{
public class Course : Entity
{
public string Title { get; set; }
public One<CourseCategory> Category { get; set; }
}
public class CourseCategory : Entity
{
public string Name { get; set; }
public Many<Course> Courses { get; set; }
public CourseCategory()
=> this.InitOneToMany(() => Courses);
}
public class CourseWithCategory : Course
{
public IEnumerable<CourseCategory> Categories { get; set; }
}
public static class Program
{
private static async Task Main()
{
await DB.InitAsync("test");
var cat = new CourseCategory { Name = "category one" };
await cat.SaveAsync();
var course1 = new Course { Category = cat, Title = "first course" };
var course2 = new Course { Category = cat, Title = "second course" };
var courses = new[] { course1, course2 };
await courses.SaveAsync();
await cat.Courses.AddAsync(courses);
//option 1: transform the reference to an entity with ToEntity
var firstCourse = await DB
.Find<Course>()
.Match(c => c.ID == course1.ID)
.ExecuteSingleAsync();
var firstCourseCat = await firstCourse.Category.ToEntityAsync();
//option 2: lookup the category in a single query
var secondCourse = await DB
.Fluent<Course>()
.Match(c => c.ID == course2.ID)
.Lookup<Course, CourseCategory, CourseWithCategory>(
DB.Collection<CourseCategory>(),
c => c.Category.ID,
cc => cc.ID,
cwc => cwc.Categories)
.SingleOrDefaultAsync();
var secondCourseCat = secondCourse.Categories.FirstOrDefault();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment