Repository Pattern
Apparence
Links
Repository Pattern
- 1 Repository per resource: ItemRepository
- 1 DbContext for the whole application
Repositories/ItemRepository.cs |
public class ItemRepository : IItemRepository
{
private readonly MyAppContext context;
public ItemRepository(MyAppContext context)
{
this.context = context;
}
public async Task<IReadOnlyCollection<Item>> GetAllItemsAsync(CancellationToken cancellationToken)
{
var items = await context.Items
.Include(x => x.NavigationProperty)
.AsNoTracking()
.ToListAsync(cancellationToken);
return items;
}
public async Task<Item?> GetItemByIdAsync(int id, CancellationToken cancellationToken)
{
var item = await context.Items
.AsNoTracking()
.SingleOrDefaultAsync(x => x.Id == id, cancellationToken);
return item;
}
public async Task<IReadOnlyCollection<Item>> GetItemsByNameAsync(string name, CancellationToken cancellationToken)
{
var items = await context.Items
.Where(x => EF.Functions.Like(x.Name, $"%{name}%"))
.AsNoTracking()
.ToListAsync(cancellationToken);
return items;
}
public async Task<Item> CreateItemAsync(Item item, CancellationToken cancellationToken)
{
await context.AddAsync(item, cancellationToken);
await context.SaveChangesAsync(cancellationToken);
return item; // it now contains its id
}
public async Task<bool> UpdateItemAsync(int id, Item item, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(item);
var itemToUpdate = await context.Items.SingleOrDefaultAsync(x => x.Id == id, cancellationToken);
if (itemToUpdate is null)
{
return false; // send not found from controller then
}
itemToUpdate.Name = item.Name;
await context.SaveChangesAsync();
return true;
}
public async Task<bool> DeleteItemAsync(int id, CancellationToken cancellationToken)
{
var nbAffectedRows = await context.Items.Where(x => x.Id == id).ExecuteDeleteAsync(cancellationToken);
return nbAffectedRows == 1;
}
|