Skip to content

Instantly share code, notes, and snippets.

@zelinskiy
Created June 20, 2019 06:03
Show Gist options
  • Save zelinskiy/aca94de84f1b3e45a6f51e5d7ef78e98 to your computer and use it in GitHub Desktop.
Save zelinskiy/aca94de84f1b3e45a6f51e5d7ef78e98 to your computer and use it in GitHub Desktop.
using LibraryManagement.Data.Interfaces;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace LibraryManagement.Data.Repository
{
// This class abstracts out the most common basic operations for
// interaction with the database entities: Creating, Reading, Updating, Deleting (CRUD).
public abstract class Repository<T> : IRepository<T> where T : class
{
// This variable references the database context.
// It is used for Entity framework operations, encapsulated further within the code
protected readonly LibraryDbContext _context;
public Repository(LibraryDbContext context)
{
_context = context;
}
// Just to make is shorter and clearer
protected void Save() => _context.SaveChanges();
// Abstact Creation operation basically abstracts out
// the simplest Entity framework scenario
// Expand it within the definitions of inherited repos to
// add more specific functionality, such as
// more complex check-ins, etc.
public void Create(T entity)
{
_context.Add(entity);
Save();
}
// Common method for entity removal
public virtual void Delete(T entity)
{
_context.Remove(entity);
Save();
}
// Common method for entities reading from the database.
public IEnumerable<T> GetAll()
{
return _context.Set<T>();
}
// Common method for entity retreival
public T GetById(int id)
{
return _context.Set<T>().Find(id);
}
// Common method for entity updates
public void Update(T entity)
{
_context.Entry(entity).State = EntityState.Modified;
Save();
}
// Common method for entity retreival based on a predicate
public IEnumerable<T> Find(Func<T, bool> predicate)
{
return _context.Set<T>().Where(predicate);
}
// Common method for getting number of entities
public int Count(Func<T, Boolean> predicate)
{
return _context.Set<T>().Where(predicate).Count();
}
// Common method for checking whether any entity satisfying the given
// condition exist
public bool Any(Func<T, bool> predicate)
{
return _context.Set<T>().Any(predicate);
}
// Common method for checking whether the SQL table is not empty
public bool Any()
{
return _context.Set<T>().Any();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment