Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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