-
-
Notifications
You must be signed in to change notification settings - Fork 80
/
Copy pathRepository.cs
88 lines (76 loc) · 2.82 KB
/
Repository.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
87
88
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using LinkDotNet.Blog.Domain;
using Microsoft.EntityFrameworkCore;
namespace LinkDotNet.Blog.Infrastructure.Persistence.Sql;
public sealed class Repository<TEntity> : IRepository<TEntity>
where TEntity : Entity
{
private readonly IDbContextFactory<BlogDbContext> dbContextFactory;
public Repository(IDbContextFactory<BlogDbContext> dbContextFactory)
{
this.dbContextFactory = dbContextFactory;
}
public async ValueTask<TEntity> GetByIdAsync(string id)
{
await using var blogDbContext = await dbContextFactory.CreateDbContextAsync();
return await blogDbContext.Set<TEntity>().SingleOrDefaultAsync(b => b.Id == id);
}
public async ValueTask<IPagedList<TEntity>> GetAllAsync(
Expression<Func<TEntity, bool>> filter = null,
Expression<Func<TEntity, object>> orderBy = null,
bool descending = true,
int page = 1,
int pageSize = int.MaxValue)
{
return await GetAllByProjectionAsync(s => s, filter, orderBy, descending, page, pageSize);
}
public async ValueTask<IPagedList<TProjection>> GetAllByProjectionAsync<TProjection>(
Expression<Func<TEntity, TProjection>> selector,
Expression<Func<TEntity, bool>> filter = null,
Expression<Func<TEntity, object>> orderBy = null,
bool descending = true,
int page = 1,
int pageSize = int.MaxValue)
{
ArgumentNullException.ThrowIfNull(selector);
await using var blogDbContext = await dbContextFactory.CreateDbContextAsync();
var entity = blogDbContext.Set<TEntity>().AsNoTracking().AsQueryable();
if (filter != null)
{
entity = entity.Where(filter);
}
if (orderBy != null)
{
entity = descending
? entity.OrderByDescending(orderBy)
: entity.OrderBy(orderBy);
}
return await entity.Select(selector).ToPagedListAsync(page, pageSize);
}
public async ValueTask StoreAsync(TEntity entity)
{
await using var blogDbContext = await dbContextFactory.CreateDbContextAsync();
if (string.IsNullOrEmpty(entity.Id))
{
await blogDbContext.Set<TEntity>().AddAsync(entity);
}
else
{
blogDbContext.Entry(entity).State = EntityState.Modified;
}
await blogDbContext.SaveChangesAsync();
}
public async ValueTask DeleteAsync(string id)
{
var entityToDelete = await GetByIdAsync(id);
if (entityToDelete != null)
{
await using var blogDbContext = await dbContextFactory.CreateDbContextAsync();
blogDbContext.Remove(entityToDelete);
await blogDbContext.SaveChangesAsync();
}
}
}