|
| 1 | +using CodeHubDesktop.Models; |
| 2 | +using Microsoft.EntityFrameworkCore; |
| 3 | +using Microsoft.EntityFrameworkCore.ChangeTracking; |
| 4 | +using System; |
| 5 | +using System.Collections.Generic; |
| 6 | +using System.Linq; |
| 7 | +using System.Threading.Tasks; |
| 8 | + |
| 9 | +namespace CodeHubDesktop.Data.Services |
| 10 | +{ |
| 11 | + public class GenericDataService<T> : IDataService<T> where T : DomainObject |
| 12 | + { |
| 13 | + public async Task<T> CreateSnippet(T entity) |
| 14 | + { |
| 15 | + using (SimpleDbContext db = new SimpleDbContext()) |
| 16 | + { |
| 17 | + EntityEntry<T> createdResult = await db.Set<T>().AddAsync(entity); |
| 18 | + await db.SaveChangesAsync(); |
| 19 | + return createdResult.Entity; |
| 20 | + } |
| 21 | + } |
| 22 | + |
| 23 | + public async Task<bool> DeleteSnippet(int id) |
| 24 | + { |
| 25 | + using (SimpleDbContext db = new SimpleDbContext()) |
| 26 | + { |
| 27 | + T entity = await db.Set<T>().FirstOrDefaultAsync((e) => e.Id == id); |
| 28 | + db.Set<T>().Remove(entity); |
| 29 | + await db.SaveChangesAsync(); |
| 30 | + return true; |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + public async Task<IEnumerable<T>> GetAllSnippets() |
| 35 | + { |
| 36 | + using (SimpleDbContext db = new SimpleDbContext()) |
| 37 | + { |
| 38 | + IEnumerable<T> entities = await db.Set<T>().ToListAsync(); |
| 39 | + return entities; |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + public async Task<IEnumerable<T>> GetSnippet(string filter) |
| 44 | + { |
| 45 | + using (SimpleDbContext db = new SimpleDbContext()) |
| 46 | + { |
| 47 | + IEnumerable<T> entities = await db.Set<T>().Where(x => x.Title.Contains(filter)).ToListAsync(); |
| 48 | + return entities; |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + public async Task<T> UpdateSnippet(int id, T entity) |
| 53 | + { |
| 54 | + using (SimpleDbContext db = new SimpleDbContext()) |
| 55 | + { |
| 56 | + entity.Id = id; |
| 57 | + |
| 58 | + db.Set<T>().Update(entity); |
| 59 | + await db.SaveChangesAsync(); |
| 60 | + return entity; |
| 61 | + } |
| 62 | + } |
| 63 | + } |
| 64 | +} |
0 commit comments