Created
December 12, 2020 09:47
-
-
Save dj-nitehawk/9c34d5e3ab23ac56b38ee08c6a6f8024 to your computer and use it in GitHub Desktop.
lookup one to many relationship
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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