blob: aae5791b281fc515c647c965f1637762a4dafe6d (
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
69
70
71
72
73
|
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Data.Models.Interfaces.Database;
using Microsoft.EntityFrameworkCore;
using Data.Models.Classes;
using System.Diagnostics;
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 IEnumerable<TEntity> Query(int count)
{
return this._context
.Set<TEntity>()
.AsNoTracking()
.Take(count)
.AsEnumerable();
}
//Update
public async Task EditAsync(object id, TEntity newEntity)
{
TEntity entity = await FindByIdAsync(id);
typeof(TEntity).GetProperty("Id").SetValue(newEntity, 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();
}
public DbSet<TEntity> DbSet => this._context.Set<TEntity>();
}
}
|