-
Notifications
You must be signed in to change notification settings - Fork 88
/
Copy pathProductRepository.cs
73 lines (63 loc) · 2.23 KB
/
ProductRepository.cs
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
69
70
71
72
73
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AspnetRunBasics.Data;
using AspnetRunBasics.Entities;
using AspnetRunBasics.Repositories.Interfaces;
using Microsoft.EntityFrameworkCore;
namespace AspnetRunBasics.Repositories
{
public class ProductRepository : IProductRepository
{
protected readonly AspnetRunContext _dbContext;
public ProductRepository(AspnetRunContext dbContext)
{
_dbContext = dbContext ?? throw new ArgumentNullException(nameof(dbContext));
}
public async Task<IEnumerable<Product>> GetProducts()
{
return await _dbContext.Products.ToListAsync();
}
public async Task<Product> GetProductById(int id)
{
return await _dbContext.Products
.Include(p => p.Category)
.FirstOrDefaultAsync(p => p.Id == id);
}
public async Task<IEnumerable<Product>> GetProductByName(string name)
{
return await _dbContext.Products
.Include(p => p.Category)
.Where(p => string.IsNullOrEmpty(name) || p.Name.ToLower().Contains(name.ToLower()))
.OrderBy(p => p.Name)
.ToListAsync();
}
public async Task<IEnumerable<Product>> GetProductByCategory(int categoryId)
{
return await _dbContext.Products
.Where(x => x.CategoryId == categoryId)
.ToListAsync();
}
public async Task<Product> AddAsync(Product product)
{
_dbContext.Products.Add(product);
await _dbContext.SaveChangesAsync();
return product;
}
public async Task UpdateAsync(Product product)
{
_dbContext.Entry(product).State = EntityState.Modified;
await _dbContext.SaveChangesAsync();
}
public async Task DeleteAsync(Product product)
{
_dbContext.Products.Remove(product);
await _dbContext.SaveChangesAsync();
}
public async Task<IEnumerable<Category>> GetCategories()
{
return await _dbContext.Categories.ToListAsync();
}
}
}