-
Notifications
You must be signed in to change notification settings - Fork 0
/
EfRepository.cs
54 lines (42 loc) · 1.74 KB
/
EfRepository.cs
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
using ListGenerator.Data.Interfaces;
using ListGeneratorListGenerator.Data.DB;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace ListGenerator.Data.Repositories
{
public class EfRepository<TEntity> : IRepository<TEntity>
where TEntity : class
{
public EfRepository(ApplicationDbContext context)
{
this.Context = context ?? throw new ArgumentNullException(nameof(context));
this.DbSet = this.Context.Set<TEntity>();
}
protected DbSet<TEntity> DbSet { get; set; }
protected ApplicationDbContext Context { get; set; }
public virtual IQueryable<TEntity> All() => this.DbSet;
public virtual IQueryable<TEntity> AllAsNoTracking() => this.DbSet.AsNoTracking();
public virtual Task<List<TSource>> ConvertToListAsync<TSource>([NotNullAttribute] IQueryable<TSource> source, CancellationToken cancellationToken = default)
{
return source.ToListAsync(cancellationToken);
}
public virtual void Add(TEntity entity) => this.DbSet.Add(entity);
public virtual void Update(TEntity entity)
{
var entry = this.Context.Entry(entity);
if (entry.State == EntityState.Detached)
{
this.DbSet.Attach(entity);
}
entry.State = EntityState.Modified;
}
public virtual void Delete(TEntity entity) => this.DbSet.Remove(entity);
public Task<int> SaveChangesAsync() => this.Context.SaveChangesAsync();
public void SaveChanges() => this.Context.SaveChanges();
}
}