-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathRepository.cs
More file actions
334 lines (297 loc) 路 12.8 KB
/
Copy pathRepository.cs
File metadata and controls
334 lines (297 loc) 路 12.8 KB
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
锘縰sing System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Reflection;
using System.Collections;
using Microsoft.EntityFrameworkCore;
using DynamicRepository.Filter;
using DynamicRepository.Extensions;
using System.Threading.Tasks;
using System.Threading;
namespace DynamicRepository.EFCore
{
/// <summary>
/// Base repository for persistency model CRUD and advanced filtering operations.
/// </summary>
/// <typeparam name="Key">The key type of current entity type. For composed primary keys use a new class type definition or an <see cref="object[]"/> array.</typeparam>
/// <typeparam name="Entity">The type of the entity being persisted or retrieved.</typeparam>
public abstract class Repository<Key, Entity> : IRepository<Key, Entity> where Entity : class, new()
{
private DataPager<Key, Entity> _dataSourcePager;
/// <summary>
/// Current EF DBContext instance.
/// </summary>
protected DbContext Context { get; set; }
/// <summary>
/// DBSet of <see cref="Entity"/> extracted from <see cref="Context"/>.
/// </summary>
protected internal DbSet<Entity> DbSet;
/// <summary>
/// Global filter instance set by <see cref="HasGlobalFilter(Expression{Func{Entity, bool}})" />
/// </summary>
private Expression<Func<Entity, bool>> GlobalFilter { get; set; }
/// <summary>
/// Default constructor of main repository.
/// Required dependencies are injected.
/// </summary>
/// <param name="context">Current EF context.</param>
public Repository(DbContext context)
{
Context = context;
// Configures current entity DB Set which is being manipulated
DbSet = context.Set<Entity>();
_dataSourcePager = new DataPager<Key, Entity>();
}
/// <summary>
/// Adds a global filter expression to all operations which query for data.
/// </summary>
/// <remarks>This method was inspired by "HasQueryFilter" found on EF Core.</remarks>
public void HasGlobalFilter(Expression<Func<Entity, bool>> filter)
{
GlobalFilter = filter;
}
/// <summary>
/// Gets an entity instance based on its <see cref="Key"/>.
/// </summary>
/// <param name="key">The desired entity key value.</param>
/// <returns>Persisted entity if found, otherwise NULL.</returns>
public virtual Entity Get(Key key)
{
Entity queriedEntity;
if (key is Array)
{
// This is to handle entity framework find by composite key
queriedEntity = DbSet.Find((key as IEnumerable).Cast<object>().ToArray());
}
else
{
queriedEntity = DbSet.Find(key);
}
return GlobalFilter != null && queriedEntity != null ? new[] { queriedEntity }.AsQueryable().FirstOrDefault(GlobalFilter) : queriedEntity;
}
/// <summary>
/// Gets an entity instance based on its <see cref="Key"/>.
/// </summary>
/// <param name="key">The desired entity key value.</param>
/// <returns>Persisted entity if found, otherwise NULL.</returns>
public virtual Task<Entity> GetAsync(Key key)
{
return GetAsync(key, CancellationToken.None);
}
/// <summary>
/// Gets an entity instance based on its <see cref="Key"/>.
/// </summary>
/// <param name="key">The desired entity key value.</param>
/// <param name="cancellationToken">A token used for cancelling propagation.</param>
/// <returns>Persisted entity if found, otherwise NULL.</returns>
public virtual async Task<Entity> GetAsync(Key key, CancellationToken cancellationToken)
{
Entity queriedEntity;
if (key is Array)
{
// This is to handle entity framework find by composite key
queriedEntity = await DbSet.FindAsync((key as IEnumerable).Cast<object>().ToArray(), cancellationToken: cancellationToken);
}
else
{
queriedEntity = await DbSet.FindAsync(new object[] { key }, cancellationToken: cancellationToken);
}
return GlobalFilter != null && queriedEntity != null ? await new[] { queriedEntity }.AsQueryable().FirstOrDefaultAsync(GlobalFilter) : queriedEntity;
}
/// <summary>
/// Persists a new entity model.
/// </summary>
/// <param name="entity">The new <see cref="Entity"/> instance to be persisted.</param>
public virtual void Insert(Entity entity)
{
DbSet.Add(entity);
}
/// <summary>
/// Persists a new entity model.
/// </summary>
/// <param name="entity">The new <see cref="Entity"/> instance to be persisted.</param>
public virtual Task InsertAsync(Entity entity)
{
return InsertAsync(entity, CancellationToken.None);
}
/// <summary>
/// Persists a new entity model.
/// </summary>
/// <param name="entity">The new <see cref="Entity"/> instance to be persisted.</param>
/// <param name="cancellationToken">A token used for cancelling propagation.</param>
public virtual Task InsertAsync(Entity entity, CancellationToken cancellationToken)
{
return DbSet.AddAsync(entity, cancellationToken).AsTask();
}
/// <summary>
/// Updates an existing persisted entity.
/// </summary>
/// <param name="entityToUpdate">The <see cref="Entity"/> instance to be updated.</param>
public virtual void Update(Entity entityToUpdate)
{
Context.Entry(entityToUpdate).State = EntityState.Modified;
}
/// <summary>
/// Updates an existing persisted entity.
/// </summary>
/// <param name="entityToUpdate">The <see cref="Entity"/> instance to be updated.</param>
public virtual Task UpdateAsync(Entity entityToUpdate)
{
return UpdateAsync(entityToUpdate, CancellationToken.None);
}
/// <summary>
/// Updates an existing persisted entity.
/// </summary>
/// <param name="entityToUpdate">The <see cref="Entity"/> instance to be updated.</param>
/// <param name="cancellationToken">A token used for cancelling propagation.</param>
public virtual Task UpdateAsync(Entity entityToUpdate, CancellationToken cancellationToken)
{
return Task.Run(() => Context.Entry(entityToUpdate).State = EntityState.Modified);
}
/// <summary>
/// Deletes an existing entity.
/// </summary>
/// <param name="id">The primary key of the <see cref="Entity"/> to be deleted.</param>
public virtual void Delete(Key id)
{
Delete(Get(id));
}
/// <summary>
/// Deletes an existing entity.
/// </summary>
/// <param name="id">The primary key of the <see cref="Entity"/> to be deleted.</param>
public virtual async Task DeleteAsync(Key id)
{
await DeleteAsync(id, CancellationToken.None);
}
/// <summary>
/// Deletes an existing entity.
/// </summary>
/// <param name="id">The primary key of the <see cref="Entity"/> to be deleted.</param>
/// <param name="cancellationToken">A token used for cancelling propagation.</param>
public virtual async Task DeleteAsync(Key id, CancellationToken cancellationToken)
{
await DeleteAsync(await GetAsync(id, cancellationToken), cancellationToken);
}
/// <summary>
/// Deletes an existing entity.
/// </summary>
/// <param name="entityToDelete">The <see cref="Entity"/> instance to be deleted.</param>
public void Delete(Entity entityToDelete)
{
if (entityToDelete != null)
{
DbSet.Remove(entityToDelete);
}
}
/// <summary>
/// Deletes an existing entity.
/// </summary>
/// <param name="entityToDelete">The <see cref="Entity"/> instance to be deleted.</param>
public Task DeleteAsync(Entity entityToDelete)
{
return DeleteAsync(entityToDelete, CancellationToken.None);
}
/// <summary>
/// Deletes an existing entity.
/// </summary>
/// <param name="entityToDelete">The <see cref="Entity"/> instance to be deleted.</param>
/// <param name="cancellationToken">A token used for cancelling propagation.</param>
public Task DeleteAsync(Entity entityToDelete, CancellationToken cancellationToken)
{
if (entityToDelete != null)
{
return Task.Run(() => DbSet.Remove(entityToDelete));
}
return Task.CompletedTask;
}
/// <summary>
/// Returns all entries of this entity.
/// </summary>
public IEnumerable<Entity> ListAll()
{
return GetQueryable();
}
/// <summary>
/// Gets a queryable instance of the current data set.
/// </summary>
public IQueryable<Entity> GetQueryable()
{
return GlobalFilter != null ? DbSet.AsQueryable().Where(GlobalFilter) : DbSet.AsQueryable();
}
/// <summary>
/// Filter, order and join the current entity based on criterias supplied as parameters.
/// </summary>
/// <param name="filter">Expression which supplies all desired filters.</param>
/// <param name="orderBy">Projetion to order the result.</param>
/// <param name="includeProperties">
/// Navigation properties that should be included on this query result.
/// Ignore this if you have lazy loading enabled.
/// </param>
/// <returns>Fullfilled collection based on the criteria.</returns>
public IEnumerable<Entity> List(
Expression<Func<Entity, bool>> filter = null,
Func<IQueryable<Entity>, IOrderedQueryable<Entity>> orderBy = null,
params string[] includeProperties)
{
IQueryable<Entity> query = GetQueryable();
if (filter != null)
{
query = query.Where(filter);
}
foreach (var includeProperty in includeProperties)
{
query = query.Include(includeProperty);
}
if (orderBy != null)
{
return orderBy(query).ToList();
}
else
{
return query.ToList();
}
}
/// <summary>
/// Returns a collection of data results that can be paged.
/// </summary>
/// <param name="settings">Settings for the search.</param>
/// <returns>Filled PagedData instance.</returns>
public IPagedDataResult<Entity> GetPagedData(PagedDataSettings settings)
{
return _dataSourcePager.GetPagedData(GetQueryable(), settings, AddPreConditionsPagedDataFilter(settings), AddExtraPagedDataFilter(settings));
}
/// <summary>
/// Adds extra filter to PagedData method.
/// </summary>
/// <remarks>
/// Override this method in <see cref="Repository{Key, Entity}{Key, Entity}"/> implementation
/// if you want to add custom filter to your paged data source.
/// </remarks>
/// <param name="settings">Current filter settings supplied by the consumer.</param>
/// <returns>Expression to be embedded to the IQueryable filter instance.</returns>
protected virtual Expression<Func<Entity, bool>> AddExtraPagedDataFilter(PagedDataSettings settings)
{
// Needs to be overriden by devs to add behavior to this.
// Change the injected filter on concrete repositories.
return null;
}
/// <summary>
/// Adds precondition global filters to paged data source.
/// Rely on this if you want to add security filters.
/// </summary>
/// <remarks>
/// Override this method in <see cref="Repository{Key, Entity}{Key, Entity}"/> implementation
/// if you want to add pre conditions global filters to your paged data source.
/// </remarks>
/// <param name="settings">Current filter settings supplied by the consumer.</param>
/// <returns>Expression to be embedded to the IQueryable filter instance.</returns>
protected virtual Expression<Func<Entity, bool>> AddPreConditionsPagedDataFilter(PagedDataSettings settings)
{
// Needs to be overriden by devs to add behavior to this.
return null;
}
}
}