MongoExtensions / src / MongoExample / MongoExtensions.cs
Code · 57 lines · 1400 bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57using MongoDB.Driver;
using System.Configuration;
using System.Linq.Expressions;


namespace MongoDb.Extensions;

public static class LinqExtensions
{
	public static IFindFluent<T, T>? Where<T>(this IMongoCollection<T> collection, Expression<Func<T, bool>> filter)
	{
		return collection.Find(filter);
	}

	public static T? FirstOrDefault<T>(this IMongoCollection<T> collection, Expression<Func<T, bool>> filter)
	{
		var results = collection.Find(filter);

		return results.FirstOrDefault();
	}

	public async static Task<T?> FirstOrDefaultAsync<T>(this IMongoCollection<T> collection, Expression<Func<T, bool>> filter)
	{
		var results = await collection.FindAsync(filter);

		if (results == null)
			return default;
		else
			return await results.FirstOrDefaultAsync();
	}

	public async static Task<List<T>> ToListAsync<T>(this IMongoCollection<T> collection, Expression<Func<T, bool>> filter)
	{
		var results = await collection.FindAsync(filter);

		if (results == null)
			return [];
		else
			return await results.ToListAsync();
	}
}

public class MongoDbContext
{
	public readonly MongoClient Client;

	private readonly IMongoDatabase db;

	public MongoDbContext(string name)
	{
		Client = new(ConfigurationManager.ConnectionStrings[name].ConnectionString);

		db = Client.GetDatabase(name);
	}

	public IMongoCollection<T> Table<T>() => db.GetCollection<T>($"{typeof(T).Name}Table");
}