Skip to content

Instantly share code, notes, and snippets.

@dj-nitehawk
Created November 26, 2020 04:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dj-nitehawk/68f866092066f6a0c58326276e920172 to your computer and use it in GitHub Desktop.
Save dj-nitehawk/68f866092066f6a0c58326276e920172 to your computer and use it in GitHub Desktop.
reverse relationship access with many-to-many relationship
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