Skip to content

Instantly share code, notes, and snippets.

@dj-nitehawk

dj-nitehawk/Program.cs

Last active Nov 13, 2020
Embed
What would you like to do?
one-to-many entity relationship example
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