Created
November 26, 2020 04:31
-
-
Save dj-nitehawk/68f866092066f6a0c58326276e920172 to your computer and use it in GitHub Desktop.
reverse relationship access with many-to-many relationship
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 TestApplication | |
{ | |
public class User : Entity | |
{ | |
[OwnerSide] | |
public Many<Client> Clients { get; set; } | |
public User() | |
{ | |
this.InitManyToMany(() => Clients, c => c.Users); | |
} | |
} | |
public class Client : Entity | |
{ | |
[InverseSide] | |
public Many<User> Users { get; set; } | |
public Client() | |
{ | |
this.InitManyToMany(() => Users, u => u.Clients); | |
} | |
} | |
public static class Program | |
{ | |
private static async Task Main() | |
{ | |
await DB.InitAsync("test"); | |
var user = new User(); | |
await user.SaveAsync(); | |
var client = new Client(); | |
await client.SaveAsync(); | |
await user.Clients.AddAsync(client); | |
await client.Users.AddAsync(user); | |
//option 1 client-side lookup | |
var userID = await new User().Clients | |
.JoinQueryable() | |
.Where(j => j.ChildID == client.ID) | |
.Select(j => j.ParentID) | |
.SingleOrDefaultAsync(); | |
var userEntity = await DB | |
.Find<User>() | |
.Match(userID) | |
.ExecuteSingleAsync(); | |
//option 2 via parents queryable | |
var user_Entity = await new User().Clients | |
.ParentsQueryable<User>(client.ID) | |
.SingleOrDefaultAsync(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment