Almost all of generic repository pattern tutorials were making use of EF, so I haven't got much sources to compare my code with. Here is what I have done. Could you please suggest me to fix my wrongs if I have or improve the code?
Note: I am using Dapper.Net as ORM, and I am aware of Dapper.Contrib dll, I just want to implement my own methods.
Generic Repository class
public interface IRepository<T> where T : BaseEntity
{
IDbConnection Connection { get; set; }
void Insert(T entity);
void Delete(T entity);
T GetById(int id);
IQueryable<T> GetAll();
}
A Repository Class
public interface ICustomerRepository : IRepository<Customer>
{
}
public class CustomerRepository : ICustomerRepository
{
public IDbConnection Connection { get; set; }
public CustomerRepository()
{
Connection = new SqlConnection(ConfigurationManager.ConnectionStrings["default"].ConnectionString);
}
public void Delete(Customer entity)
{
try
{
using (Connection)
{
Connection.Execute("DELETE FROM dbo.Customer Where Id = @Id", new { entity.Id });
}
}
catch (Exception ex)
{
}
}
public IQueryable<Customer> GetAll()
{
IQueryable<Customer> list = new List<Customer>().AsQueryable();
try
{
using (Connection)
{
list = Connection.Query<Customer>("SELECT * FROM dbo.Customer").AsQueryable();
}
}
catch (Exception ex)
{
}
return list;
}
public Customer GetById(int id)
{
Customer customer = new Customer();
try
{
using (Connection)
{
customer = Connection.Query<Customer>("SELECT * FROM dbo.Customer WHERE Id = @Id", new { Id = id }).SingleOrDefault();
}
}
catch (Exception ex)
{
}
return customer;
}
public void Insert(Customer entity)
{
try
{
using (Connection)
{
Connection.Execute("INSERT INTO dbo.Customer VALUES(@FullName, @TcNo, @BirthDate)",
new
{
entity.FullName,
entity.Tcno,
entity.BirthDate
});
}
}
catch (Exception ex)
{
}
}
}
An Api Controller
public class CustomerController : ApiController
{
private IRepository<Customer> _customerRepo;
public CustomerController()
{
_customerRepo = new CustomerRepository(new SqlConnection(ConfigurationManager.ConnectionStrings["default"].ConnectionString));
}
[HttpGet]
[Route("")]
public IHttpActionResult Get()
{
return Json(_customerRepo.GetAll());
}
}