forked from unrealbg/BlazorBlog
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCategoryRepository.cs
More file actions
68 lines (62 loc) · 2.48 KB
/
CategoryRepository.cs
File metadata and controls
68 lines (62 loc) · 2.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
namespace BlazorBlog.Repository
{
using Common;
using Data.Entities;
using Data;
using Contracts;
using Microsoft.EntityFrameworkCore;
public class CategoryRepository : ICategoryRepository
{
private readonly IDbContextFactory<ApplicationDbContext> _contextFactory;
public CategoryRepository(IDbContextFactory<ApplicationDbContext> contextFactory)
{
_contextFactory = contextFactory;
}
public async Task<Category[]> GetCategoriesAsync()
{
await using var context = await _contextFactory.CreateDbContextAsync();
return await context.Categories.AsNoTracking().ToArrayAsync();
}
public async Task<Category> SaveCategoryAsync(Category category)
{
await using var context = await _contextFactory.CreateDbContextAsync();
if (category.Id == 0)
{
var existingCategory = await context.Categories.AsNoTracking()
.AnyAsync(c => c.Name == category.Name);
if (existingCategory)
{
throw new InvalidOperationException($"Category with the name {category.Name} already exists.");
}
category.Slug = category.Name.ToSlug();
await context.Categories.AddAsync(category);
}
else
{
var dbCategory = await context.Categories.FindAsync(category.Id);
if (dbCategory != null)
{
dbCategory.Name = category.Name;
dbCategory.Slug = category.Name.ToSlug();
dbCategory.ShowOnNavBar = category.ShowOnNavBar;
}
}
await context.SaveChangesAsync();
return category;
}
public async Task<bool> DeleteCategoryAsync(int id)
{
await using var context = await _contextFactory.CreateDbContextAsync();
var category = await context.Categories.FindAsync(id);
if (category == null) return false;
context.Categories.Remove(category);
await context.SaveChangesAsync();
return true;
}
public async Task<Category?> GetCategoryBySlugAsync(string slug)
{
await using var context = await _contextFactory.CreateDbContextAsync();
return await context.Categories.AsNoTracking().FirstOrDefaultAsync(c => c.Slug == slug);
}
}
}