blob: 7ffdc505a0555e5c099f47dc12b0ada4eeb8072f (
plain)
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
|
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Reflection;
using Tango.DAL.Attributes;
using System.Linq.Expressions;
using MongoDB.Driver.Linq;
using System.Linq;
using Newtonsoft.Json;
namespace Tango.DAL.Mongo
{
public class MongoRepository<T> : IRepository<T> where T : Entity
{
private IMongoDatabase _database;
private MongoClient _client;
private IMongoCollection<T> _collection;
public MongoRepository(MongoDataBaseSettings settings)
{
_client = new MongoClient(settings.Address);
_database = _client.GetDatabase(settings.DatabaseName);
}
public MongoRepository(IMongoDatabase database)
{
_database = database;
}
private IMongoCollection<T> GetCollection()
{
if (_collection == null)
{
_collection = _database.GetCollection<T>(typeof(T).GetCustomAttribute<CollectionAttribute>().Name);
foreach (var prop in typeof(T).GetProperties())
{
if (prop.GetCustomAttribute<UniqueAttribute>() != null)
{
var indices = _collection.Indexes.List().ToList().Select(x => JsonConvert.DeserializeObject<MongoIndex>(x.ToString())).ToList();
if (!indices.Exists(x => x.name == prop.Name))
{
var builder = Builders<T>.IndexKeys;
var indexModel = new CreateIndexModel<T>(builder.Ascending(prop.Name), new CreateIndexOptions()
{
Unique = true,
Name = prop.Name,
});
_collection.Indexes.CreateOne(indexModel);
}
}
}
}
return _collection;
}
public async Task<List<T>> GetAllAsync()
{
return await (await GetCollection().FindAsync(x => true)).ToListAsync();
}
public async Task<List<T>> GetAsync(Expression<Func<T, bool>> filter)
{
return await (await GetCollection().FindAsync(filter)).ToListAsync();
}
public async Task<T> ReplaceAsync(T entity)
{
await GetCollection().ReplaceOneAsync(x => x.ID == entity.ID, entity);
return entity;
}
public async Task<long> DeleteAsync(Expression<Func<T, bool>> filter)
{
return (await GetCollection().DeleteOneAsync(filter)).DeletedCount;
}
public async Task<T> Insert(T entity)
{
await GetCollection().InsertOneAsync(entity);
return entity;
}
public Task<long> Count()
{
return GetCollection().CountDocumentsAsync(x => true);
}
public Task<long> Count(Expression<Func<T, bool>> filter)
{
return GetCollection().CountDocumentsAsync(filter);
}
public void Dispose()
{
}
}
}
|