Advertisement
Superstar

BaseRepository - Dapper + EFC (Main) sample

Sep 16th, 2023
1,029
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.26 KB | None | 0 0
  1. using System.Collections.Generic;
  2. using System.Linq;
  3. using Dapper;
  4. using Microsoft.EntityFrameworkCore;
  5.  
  6. namespace MyProject
  7. {
  8.     public class Repository<T> : IRepository<T> where T : class
  9.     {
  10.         private readonly DbContext _context;
  11.  
  12.         public Repository(DbContext context)
  13.         {
  14.             _context = context;
  15.         }
  16.  
  17.         public IEnumerable<T> GetAll()
  18.         {
  19.             return _context.Set<T>().AsEnumerable();
  20.         }
  21.  
  22.         public void Add(T entity)
  23.         {
  24.             _context.Set<T>().Add(entity);
  25.             _context.SaveChanges();
  26.         }
  27.  
  28.         public void Update(T entity)
  29.         {
  30.             _context.Set<T>().Update(entity);
  31.             _context.SaveChanges();
  32.         }
  33.  
  34.         public void Delete(T entity)
  35.         {
  36.             _context.Set<T>().Remove(entity);
  37.             _context.SaveChanges();
  38.         }
  39.  
  40.         public T GetById(int id)
  41.         {
  42.             return _context.Set<T>().Find(id);
  43.         }
  44.  
  45.         public IEnumerable<T> GetByRawSql(string query, object parameters)
  46.         {
  47.             using (var connection = _context.Database.GetDbConnection())
  48.             {
  49.                 return connection.Query<T>(query, parameters);
  50.             }
  51.         }
  52.     }
  53. }
  54.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement