Last active
July 7, 2021 12:40
-
-
Save dj-nitehawk/9971a57062f32fac8e7597a889d47714 to your computer and use it in GitHub Desktop.
one-to-many entity relationship example
This file contains 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.Linq; | |
using System.Threading.Tasks; | |
namespace ReferencedRelationshipExample | |
{ | |
public class Author : Entity | |
{ | |
public string Name { get; set; } | |
public Many<Book> Books { get; set; } | |
public Author() => this.InitOneToMany(() => Books); | |
} | |
public class Book : Entity | |
{ | |
public string Title { get; set; } | |
public One<Author> Author { get; set; } | |
} | |
public class AuthorWithBooks : Author | |
{ | |
public Book[] AllBooks { get; set; } | |
} | |
public static class Program | |
{ | |
private static async Task Main() | |
{ | |
await DB.InitAsync("test"); | |
//create author and his books | |
var author = new Author { Name = "Author One" }; | |
await author.SaveAsync(); | |
var books = new[] { | |
new Book { Title = "Book One", Author = author }, | |
new Book { Title = "Book Two", Author = author } | |
}; | |
await books.SaveAsync(); | |
await author.Books.AddAsync(books); | |
//retrieve all books of author | |
var allBooks = await author.Books | |
.ChildrenQueryable() | |
.ToListAsync(); | |
//retrieve first book of author | |
var firstBook = await author.Books | |
.ChildrenQueryable() | |
.Where(b => b.Title == "Book One") | |
.ToListAsync(); | |
//retrieve author together with all of his books | |
var authorWithBooks = await DB.Fluent<Author>() | |
.Match(a => a.ID == author.ID) | |
.Lookup<Author, Book, AuthorWithBooks>( | |
DB.Collection<Book>(), | |
a => a.ID, | |
b => b.Author.ID, | |
awb => awb.AllBooks) | |
.ToListAsync(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment