Mid From PDF SOLID Design Patterns & SOLID

How do you implement Repository pattern with Entity Framework?

Here's a basic example:

// Entity

public class Product
{
public int Id { get; set; }
public string Name { get; set; }
}

// Generic Repository Interface

public interface IRepository<T> where T : class
{

Task<IEnumerable<T>> GetAllAsync();

Task<T> GetByIdAsync(int id);

Task AddAsync(T entity);

void Update(T entity);

void Delete(T entity);

Task SaveAsync();

}

// EF Core implementation

public class Repository<T> : IRepository<T> where T : class
{
private readonly DbContext _context;
private readonly DbSet<T> _dbSet;
public Repository(DbContext context)
{
_context = context;
_dbSet = context.Set<T>();
}
public async Task<IEnumerable<T>> GetAllAsync() => await

_dbSet.ToListAsync();

public async Task<T> GetByIdAsync(int id) => await

_dbSet.FindAsync(id);

public async Task AddAsync(T entity) => await

_dbSet.AddAsync(entity);

public void Update(T entity) => _dbSet.Update(entity);
public void Delete(T entity) => _dbSet.Remove(entity);
public async Task SaveAsync() => await

_context.SaveChangesAsync();

}

More from Design Patterns in C#

All questions for this course
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details