Last active
April 12, 2021 16:51
-
-
Save PadreSVK/cd4878709cf41a994207c01817fc0807 to your computer and use it in GitHub Desktop.
Dummy repository implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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