-
Notifications
You must be signed in to change notification settings - Fork 0
/
BaseRepo.cs
86 lines (70 loc) · 2.53 KB
/
BaseRepo.cs
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
namespace AgileWall.Domain.Repo
{
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Collections.Generic;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
using MongoDB.Driver.Linq;
using Utils;
using Entity;
public class BaseRepo<TEntity> : IBaseRepo<TEntity> where TEntity : BaseEntity
{
private readonly MongoDatabase _mongoDatabase;
private readonly MongoCollection<TEntity> _collection;
public BaseRepo(string dbName = Consts.DBName)
{
_mongoDatabase = new MongoClient().GetServer().GetDatabase(dbName);
_collection = _mongoDatabase.GetCollection<TEntity>(typeof(TEntity).Name, WriteConcern.Acknowledged);
}
public MongoCursor<TEntity> FindAll()
{
return _collection.FindAllAs<TEntity>();
}
public IQueryable<TEntity> AsQueryable()
{
return _collection.AsQueryable().Where(x => !x.IsDeleted);
}
public IQueryable<TEntity> AsOrderedQueryable()
{
if (!_collection.IndexExists("CreatedOn"))
{
_collection.CreateIndex("CreatedOn");
}
return AsQueryable().OrderByDescending(x => x.CreatedOn);
}
public TEntity GetSingle(string id)
{
return GetSingle(x => x.Id == ObjectId.Parse(id));
}
public TEntity GetSingle(Expression<Func<TEntity, bool>> expression)
{
return AsQueryable().FirstOrDefault(expression);
}
public WriteConcernResult Add(TEntity entity)
{
return _collection.Insert(entity);
}
public void AddBulk(IEnumerable<TEntity> entities)
{
_collection.InsertBatch(entities);
}
public WriteConcernResult Delete(TEntity entity)
{
return _collection.Update(Query<TEntity>.EQ(x => x.Id, entity.Id),
Update<TEntity>.Set(x => x.DeletedOn, entity.DeletedOn)
.Set(x => x.DeletedBy, entity.DeletedBy)
.Set(x => x.IsDeleted, true));
}
public WriteConcernResult DeleteAll()
{
return _collection.RemoveAll();
}
public WriteConcernResult Update(IMongoQuery mongoQuery, IMongoUpdate mongoUpdate)
{
return _collection.Update(mongoQuery, mongoUpdate);
}
}
}