dotnet --version
dotnet add package Microsoft.EntityFrameworkCore.Sqlite
Create a generic repository with a Unit of Work that coordinates multiple repositories in a single transaction.
1 using System.Linq.Expressions; 2 3 public interface IRepository<T, TKey> where T : class 4 { 5 Task<T?> GetByIdAsync(TKey id, CancellationToken ct = default); 6 Task<IReadOnlyList<T>> GetAllAsync(CancellationToken ct = default); 7 Task<IReadOnlyList<T>> FindAsync(Expression<Func<T, bool>> predicate, CancellationToken ct = default); 8 Task<T> AddAsync(T entity, CancellationToken ct = default); 9 void Update(T entity); 10 void Remove(T entity); 11 Task<int> CountAsync(Expression<Func<T, bool>>? predicate = null, CancellationToken ct = default); 12 } 13 14 public interface IUnitOfWork : IDisposable 15 { 16 IRepository<Product, int> Products { get; } 17 IRepository<Order, Guid> Orders { get; } 18 Task<int> CommitAsync(CancellationToken ct = default); 19 } 20 21 public class EfUnitOfWork : IUnitOfWork 22 { 23 private readonly AppDbContext _db; 24 25 public EfUnitOfWork(AppDbContext db) 26 { 27 _db = db; 28 Products = new EfRepository<Product, int>(_db); 29 Orders = new EfRepository<Order, Guid>(_db); 30 } 31 32 public IRepository<Product, int> Products { get; } 33 public IRepository<Order, Guid> Orders { get; } 34 35 public Task<int> CommitAsync(CancellationToken ct = default) 36 => _db.SaveChangesAsync(ct); 37 38 public void Dispose() => _db.Dispose(); 39 } 40
Sign in to share your feedback and join the discussion.