From 2bcaa82e555100ffbcf6b23dd330e7bddd67cad6 Mon Sep 17 00:00:00 2001 From: transtrike Date: Tue, 8 Dec 2020 20:38:05 +0200 Subject: DbRepository implemented --- API/Database/DbRepository.cs | 65 +++++++++++++++++++++++++++++++++- API/Database/Interfaces/IRepository.cs | 24 +++++++++++++ 2 files changed, 88 insertions(+), 1 deletion(-) create mode 100644 API/Database/Interfaces/IRepository.cs diff --git a/API/Database/DbRepository.cs b/API/Database/DbRepository.cs index a166682..5540104 100644 --- a/API/Database/DbRepository.cs +++ b/API/Database/DbRepository.cs @@ -1,4 +1,67 @@ +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Camera_Shop.Database; +using Microsoft.EntityFrameworkCore; + namespace API.Database { - + public class DbRepository : IRepository + where TEntity : class + { + private readonly DbContext _context; + public DbRepository(DbContext context) + { + _context = context; + } + + //Create + public async Task AddAsync(TEntity entity) + { + await this._context + .Set() + .AddAsync(entity); + + await this._context.SaveChangesAsync(); + } + + //Read + public async Task FindByIdAsync(object id) + { + return await this._context + .Set() + .FindAsync(id); + } + + public async Task> Query(int count) + { + return this._context + .Set() + .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().Remove(entity); + + await this._context.SaveChangesAsync(); + } + } } \ No newline at end of file diff --git a/API/Database/Interfaces/IRepository.cs b/API/Database/Interfaces/IRepository.cs new file mode 100644 index 0000000..927e006 --- /dev/null +++ b/API/Database/Interfaces/IRepository.cs @@ -0,0 +1,24 @@ +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace Camera_Shop.Database +{ + public interface IRepository + where TEntity : class + { + //Add Entity to database + Task AddAsync(TEntity entity); + + //Return *count* instances of Entity from the database + Task> Query(int count); + + //Find entity by id + Task FindByIdAsync(object id); + + //Modify Entity from database + Task EditAsync(object id, TEntity newEntity); + + //Delete Entity from database + Task DeleteAsync(object id); + } +} \ No newline at end of file -- cgit v1.2.3