کلاس IProductRepository.cs :
using System.Collections.Generic;
using System.Threading.Tasks;
using Catalog.Api.Entities;
namespace Catalog.Api.Repositories
{
public interface IProductRepository
{
Task> GetProducts();
Task GetProduct(string id);
Task> GetProductByName(string name);
Task> GetProductByCategory(string category);
Task CreateProduct(Product product);
Task UpdateProduct(Product product);
Task DeleteProduct(string id);
}
}
کلاس ProductRepository.cs
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Catalog.Api.Data;
using Catalog.Api.Entities;
using MongoDB.Driver;
namespace Catalog.Api.Repositories
{
public class ProductRepository : IProductRepository
{
#region constructor
private readonly ICatalogContext _context;
public ProductRepository(ICatalogContext catalogContext)
{
_context = catalogContext;
}
#endregion
#region product repo
public async Task> GetProducts()
{
return await _context.Products.Find(p => true).ToListAsync();
}
public async Task GetProduct(string id)
{
return await _context.Products.Find(p => p.Id == id).FirstOrDefaultAsync();
}
public async Task> GetProductByName(string name)
{
FilterDefinition filter =
Builders.Filter.Eq(p => p.Name, name);
return await _context.Products.Find(filter).ToListAsync();
}
public async Task> GetProductByCategory(string category)
{
FilterDefinition filter =
Builders.Filter.Eq(p => p.Category, category);
return await _context.Products.Find(filter).ToListAsync();
}
public async Task CreateProduct(Product product)
{
await _context.Products.InsertOneAsync(product);
}
public async Task UpdateProduct(Product product)
{
var updateResult = await _context.Products
.ReplaceOneAsync(filter: p => p.Id == product.Id, replacement: product);
return updateResult.IsAcknowledged
&& updateResult.ModifiedCount > 0;
}
public async Task DeleteProduct(string id)
{
FilterDefinition filter =
Builders.Filter.Eq(p => p.Id, id);
DeleteResult deleteResult = await _context.Products
.DeleteOneAsync(filter);
return deleteResult.IsAcknowledged
&& deleteResult.DeletedCount > 0;
}
#endregion
}
}