Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
using System;
using System.Linq;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Dapper.Contrib.Extensions;
using NorthwindApi.Model.Context;
using NorthwindApi.Model.Entity;
namespace NorthwindApi.Model.Repository
{
public interface IProductRepository : IBaseRepository<Product>
{
Task<Product> GetByID(string productCode);
Task<IList<Product>> GetByName(string productName);
}
public class ProductRepository : IProductRepository
{
private readonly IDbContext _context;
private readonly ILogger _logger;
public ProductRepository(IDbContext context, ILoggerFactory loggerFactory)
{
_context = context;
_logger = loggerFactory.CreateLogger<ProductRepository>();
}
public Task<Product> GetByID(string productCode)
{
Product obj = null;
try
{
obj = _context.Conn.GetAsync<Product>(productCode).Result;
}
catch (Exception ex)
{
if (this._logger != null) _logger.LogError(ex, "Exception");
}
return Task.FromResult(obj);
}
public Task<IList<Product>> GetByName(string productName)
{
IList<Product> list = new List<Product>();
try
{
list = _context.Conn
.GetAllAsync<Product>().Result
.Where(f => f.product_name.Contains(productName))
.OrderBy(f => f.product_name)
.ToList();
}
catch (Exception ex)
{
if (this._logger != null) _logger.LogError(ex, "Exception");
}
return Task.FromResult(list);
}
public Task<IList<Product>> GetAll()
{
IList<Product> list = new List<Product>();
try
{
list = _context.Conn
.GetAllAsync<Product>().Result
.OrderBy(f => f.product_name)
.ToList();
}
catch (Exception ex)
{
if (this._logger != null) _logger.LogError(ex, "Exception");
}
return Task.FromResult(list);
}
public Task<int> Save(Product obj)
{
var result = 0;
try
{
result = _context.Conn.InsertAsync<Product>(obj).Result;
}
catch (Exception ex)
{
if (this._logger != null) _logger.LogError(ex, "Exception");
}
return Task.FromResult(result);
}
public Task<int> Update(Product obj)
{
var result = 0;
try
{
result = _context.Conn.UpdateAsync<Product>(obj).Result ? 1 : 0;
}
catch (Exception ex)
{
if (this._logger != null) _logger.LogError(ex, "Exception");
}
return Task.FromResult(result);
}
public Task<int> Delete(Product obj)
{
var result = 0;
try
{
result = _context.Conn.DeleteAsync<Product>(obj).Result ? 1 : 0;
}
catch (Exception ex)
{
if (this._logger != null) _logger.LogError(ex, "Exception");
}
return Task.FromResult(result);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.