Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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