I have a function to return the highest value of an ID field from a table using EF Core. But I'd like to implement it in my generic repository to be dynamic and to be used by all classes. How do I do this?
//Funcionar no Repositório de Pessoa
public int GetMax()
{
return DbSet.Select(p=> p.Id).DefaultIfEmpty(0).Max();
}
//Repositório Genérico
public class Repository<TEntity> : IRepository<TEntity> where TEntity : class
{
protected readonly RetaguardaContext Db;
protected readonly DbSet<TEntity> DbSet;
public Repository(RetaguardaContext context)
{
Db = context;
DbSet = Db.Set<TEntity>();
}
public virtual void Add(TEntity obj)
{
DbSet.Add(obj);
}
public virtual TEntity GetById(int id)
{
return DbSet.Find(id);
}
public virtual IQueryable<TEntity> GetAll()
{
return DbSet;
}
public virtual void Update(TEntity obj)
{
DbSet.Update(obj);
}
public virtual void Remove(int id)
{
DbSet.Remove(DbSet.Find(id));
}
public int SaveChanges()
{
return Db.SaveChanges();
}
public void Dispose()
{
Db.Dispose();
GC.SuppressFinalize(this);
}
public void Remove(params object[] keyValues)
{
DbSet.Remove(DbSet.Find(keyValues));
}
public TEntity GetByIds(params object[] keyValues)
{
return DbSet.Find(keyValues);
}
}