Example Repositories

INTERFACES public interface IRepository where T : BaseEntity, new() { public Task AddAsync(T entity); public Task> GetAllAsync(); public Task GetByIdAsync(int Id); public Task GetByConditionAsync(Expression> condition); public void Delete(T entity); public void Update(T entity); public Task SaveChangesAsync(); } IMPLEMENTATIONS public class Repository : IRepository where T : BaseEntity, new() { readonly AppDbContext _context; public Repository(AppDbContext context) { _context = context; } DbSet Table => _context.Set(); public async Task AddAsync(T entity) { await Table.AddAsync(entity); } public void Delete(T entity) { Table.Remove(entity); } public async Task GetAllAsync() { return await Table.ToListAsync(); } public async Task GetByConditionAsync(Expression condition) { return await Table.FirstOrDefaultAsync(condition); } public async Task GetByIdAsync(int Id) { return await Table.FirstOrDefaultAsync(e => e.Id == Id); } public async Task SaveChangesAsync() { return await _context.SaveChangesAsync(); } public void Update(T entity) { Table.Update(entity); } }

Jan 23, 2025 - 02:23
 0
Example Repositories

INTERFACES
public interface IRepository where T : BaseEntity, new()
{
public Task AddAsync(T entity);
public Task> GetAllAsync();
public Task GetByIdAsync(int Id);
public Task GetByConditionAsync(Expression> condition);
public void Delete(T entity);
public void Update(T entity);
public Task SaveChangesAsync();
}

IMPLEMENTATIONS

public class Repository : IRepository where T : BaseEntity, new()
{
readonly AppDbContext _context;
public Repository(AppDbContext context)
{
_context = context;
}

DbSet Table => _context.Set();
public async Task AddAsync(T entity)
{
    await Table.AddAsync(entity);
}

public void Delete(T entity)
{
    Table.Remove(entity);
}

public async Task> GetAllAsync()
{
    return await Table.ToListAsync();
}

public async Task GetByConditionAsync(Expression> condition)
{
    return await Table.FirstOrDefaultAsync(condition);
}

public async Task GetByIdAsync(int Id)
{
    return await Table.FirstOrDefaultAsync(e => e.Id == Id);
}

public async Task SaveChangesAsync()
{
    return await _context.SaveChangesAsync();
}

public void Update(T entity)
{
    Table.Update(entity);
}

}

What's Your Reaction?

like

dislike

love

funny

angry

sad

wow