Skip to content

Instantly share code, notes, and snippets.

@PadreSVK
Last active April 12, 2021 16:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PadreSVK/cd4878709cf41a994207c01817fc0807 to your computer and use it in GitHub Desktop.
Save PadreSVK/cd4878709cf41a994207c01817fc0807 to your computer and use it in GitHub Desktop.
Dummy repository implementation
public interface IRepository<TEntity, in TId>
where TEntity : IEntity<TId>
{
Task<TEntity> GetById(TId id);
Task Insert(TEntity entity);
Task Update(TEntity entity);
Task Remove(TId id);
}
public interface IEntity<TId>
{
TId Id { get; set; }
}
public abstract class RepositoryBase<TEntity, TId>: IRepository<TEntity, TId>
where TEntity : class, IEntity<TId>, new()
where TId: struct
{
private readonly IShopContext shopContext;
protected RepositoryBase(IShopContext shopContext)
{
this.shopContext = shopContext;
}
public async virtual Task<TEntity> GetById(TId id)
{
return await shopContext.Set<TEntity>().FindAsync(id);
}
public async virtual Task Insert(TEntity entity)
{
await shopContext.Set<TEntity>().AddAsync(entity);
await shopContext.SaveChangesAsync();
}
public async virtual Task Update(TEntity entity)
{
shopContext.Set<TEntity>().Update(entity);
await shopContext.SaveChangesAsync();
}
public async virtual Task Remove(TId id)
{
var entity = new TEntity() { Id = id};
shopContext.Attach(entity);
shopContext.Remove(entity);
await shopContext.SaveChangesAsync();
}
}
public class CategoryRepository : RepositoryBase<Category, int>
{
public CategoryRepository(IShopContext shopContext) : base(shopContext)
{
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment