Last active
December 18, 2018 18:00
-
-
Save gzamudio/4ed617eb944773de6f67caf46e205cc3 to your computer and use it in GitHub Desktop.
Dapper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Linq.Expressions; | |
using Project.Repositories.Interfaces; | |
using Microsoft.EntityFrameworkCore; | |
namespace Project.Repositories | |
{ | |
public class Repository<T> : IRepository<T> where T : class | |
{ | |
private readonly DbContext _context; | |
public Repository(DbContext context) => _context = context; | |
public DbContext Context { get => _context; } | |
public void Add(T entity) | |
{ | |
return connection.Execute(@"insert into tablename (@columnName, @otherColumnName, ..., @lastColumnName);", | |
entity); | |
} | |
public void AddRange(IEnumerable<T> entities) | |
{ | |
return connection.Execute(@"insert into tablename (@columnName, @otherColumnName, ..., @lastColumnName);", | |
entities); | |
} | |
public T Get(int id) | |
{ | |
string query = "select * from tablename where id = @Id"; | |
return connection.Query<T>(query, new { Id = id }).FirstOrDefault(); | |
} | |
public IEnumerable<T> GetAll() | |
{ | |
string query = "select * from tablename"; | |
return connection.Query<T>(query).AsList(); | |
} | |
public void Remove(T entity) | |
{ | |
return connection.Execute("remove from tablename where id = @Id", { Id = T.Id }); | |
} | |
public void UpdateRange(IEnumerable<T> entities) | |
{ | |
using (var connection = Connection) | |
{ | |
using(IDbTransaction transaction = connection.BeginTransaction()) | |
{ | |
try | |
{ | |
await connection.ExecuteAsync(@"update tablename set columnname = @columnValue where id=@Id", entities, transaction); | |
transaction.Commit(); | |
} | |
catch(Exception e) | |
{ | |
transaction.Rollback(); | |
throw new Exception(e.ToString()); | |
} | |
} | |
} | |
} | |
public bool Update(T entity) | |
{ | |
using (var connection = Connection) | |
{ | |
using(IDbTransaction transaction = connection.BeginTransaction()) | |
{ | |
try | |
{ | |
await connection.ExecuteAsync(@"update tablename set columnname = @columnValue where id=@Id", entity, transaction); | |
transaction.Commit(); | |
} | |
catch(Exception e) | |
{ | |
transaction.Rollback(); | |
throw new Exception(e.ToString()); | |
} | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment