using AutomatedLibrarySyst em Data EntityFramework Interfaces using Au

 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
using AutomatedLibrarySystem.Data.EntityFramework.Interfaces;
using AutomatedLibrarySystem.Data.Infrastructure.Exceptions;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
namespace AutomatedLibrarySystem.Data.EntityFramework.Repositories {
public class LibraryRepository<TEntity> : IRepository<TEntity> where TEntity : class {
private LibraryContext context;
public LibraryRepository(LibraryContext context) {
this.context = context;
}
public void Create(TEntity entity) {
context.Entry(entity).State = EntityState.Added;
}
public void Update(TEntity entity) {
if (!context.Set<TEntity>().AsNoTracking().AsEnumerable().Contains(entity))
throw new EntityNotFoundException();
context.Entry(entity).State = EntityState.Modified;
}
public void Delete(TEntity entity) {
if (!context.Set<TEntity>().AsNoTracking().AsEnumerable().Contains(entity))
throw new EntityNotFoundException();
context.Entry(entity).State = EntityState.Deleted;
}
public void DeleteSingleBy(Expression<Func<TEntity, bool>> predicate) {
TEntity entity = context.Set<TEntity>().FirstOrDefault(predicate);
if (entity == null)
throw new EntityNotFoundException();
context.Entry(entity).State = EntityState.Deleted;
}
public void DeleteBy(Expression<Func<TEntity, bool>> predicate) {
IEnumerable<TEntity> entities = context.Set<TEntity>().Where(predicate).AsEnumerable();
if (entities.Count() == 0)
throw new EntityNotFoundException();
foreach (TEntity entity in entities)
context.Entry(entity).State = EntityState.Deleted;
}
public TEntity GetSingle(Expression<Func<TEntity, bool>> predicate) {
TEntity entity = context.Set<TEntity>().FirstOrDefault(predicate);
return entity ?? throw new EntityNotFoundException();
}
public IEnumerable<TEntity> GetAll() {
IEnumerable<TEntity> entities = context.Set<TEntity>().AsEnumerable();
if (entities.Count() == 0)
throw new EntityNotFoundException();
return entities;
}
public IEnumerable<TEntity> FindBy(Expression<Func<TEntity, bool>> predicate) {
IEnumerable<TEntity> entities = context.Set<TEntity>().Where(predicate).AsEnumerable();
if (entities.Count() == 0)
throw new EntityNotFoundException();
return entities;
}
}
}