Skip to content

Instantly share code, notes, and snippets.

@ti-ka
Last active March 23, 2024 00:45
Show Gist options
  • Save ti-ka/2e7a1be8a8282d2c0b9dd2d52d03d1e7 to your computer and use it in GitHub Desktop.
Save ti-ka/2e7a1be8a8282d2c0b9dd2d52d03d1e7 to your computer and use it in GitHub Desktop.
Generic Repository with Tracking and No Tracking Options
using Prognose.Domain;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
namespace App.Domain
{
public interface IEntity
{
int Id { get; set; }
}
}
namespace App.Repository
{
public class GenericRepository<TEntity> : IDisposable where TEntity : class, IEntity
{
internal DbContext _context;
internal DbSet<TEntity> _dbSet;
private bool _tracking = false;
public GenericRepository(DbContext context)
{
//For Injected Context
_context = context;
_dbSet = _context.Set<TEntity>();
}
public GenericRepository()
{
//For Non-Injected Context
_context = new AppDomainContext();
_dbSet = _context.Set<TEntity>();
}
public GenericRepository<TEntity> WithTracking()
{
_tracking = true;
return this;
}
public GenericRepository<TEntity> WithoutTracking()
{
_tracking = false;
return this;
}
public IQueryable<TEntity> All()
{
if (_tracking)
return _dbSet;
else
return _dbSet.AsNoTracking();
}
public IEnumerable<TEntity> FindBy(Expression<Func<TEntity, bool>> predicate)
{
if (_tracking)
return _dbSet.Where(predicate);
else
return _dbSet.AsNoTracking().Where(predicate);
}
public TEntity Find(int Id)
{
if (_tracking)
return _dbSet.Find(Id);
else
return _dbSet.AsNoTracking().Where(x => x.Id == Id).FirstOrDefault();
}
public void Insert(TEntity e)
{
_dbSet.Add(e);
}
public void Update(TEntity e)
{
if (!_tracking)
_context.Entry(e).State = EntityState.Modified;
}
public void Delete(int Id)
{
Delete(Find(Id));
}
public void Delete(TEntity e)
{
if (_tracking)
_dbSet.Remove(e);
else
_context.Entry(e).State = EntityState.Deleted;
}
public bool Exists(TEntity entity)
{
return _dbSet.Any(e => e.Id == entity.Id);
}
public void SaveContext()
{
_context.SaveChanges();
}
public void Dispose()
{
_context.Dispose();
}
}
}
@kimfom01
Copy link

You are an angel... Thank you for this!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment