aboutsummaryrefslogtreecommitdiff
path: root/API/Database/DbRepository.cs
blob: b961a548e55a939ac672535e1b885f67d34c0074 (plain) (blame)
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
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Models.Interfaces.Database;
using Microsoft.EntityFrameworkCore;

namespace API.Database
{
	public class DbRepository<TEntity> : IRepository<TEntity>
		where TEntity : class
	{
		private readonly DbContext _context;
		public DbRepository(DbContext context)
		{
			_context = context;
		}

		//Create
		public async Task AddAsync(TEntity entity)
		{
			await this._context
				.Set<TEntity>()
				.AddAsync(entity);

			await this._context.SaveChangesAsync();
		}

		//Read
		public async Task<TEntity> FindByIdAsync(object id)
		{
			return await this._context
				.Set<TEntity>()
				.FindAsync(id);
		}

		public async Task<IAsyncEnumerable<TEntity>> Query(int count)
		{
			return this._context
				.Set<TEntity>()
				.AsNoTracking()
				.Take(count)
				.AsAsyncEnumerable();
		}

		//Update
		public async Task EditAsync(object id, TEntity newEntity)
		{
			//Set the Id property to the given id
			TEntity entity = await FindByIdAsync(id);

			this._context.Entry(entity)
				.CurrentValues
				.SetValues(newEntity);

			await this._context.SaveChangesAsync();
		}

		//Delete
		public async Task DeleteAsync(object id)
		{
			TEntity entity = await FindByIdAsync(id);

			this._context.Set<TEntity>().Remove(entity);

			await this._context.SaveChangesAsync();
		}
	}
}