Filter results on a bank level Entity Framework

1

I have the following question about using the Entity Framework.

I have an abstract class for the class that communicates with the base. Aiming for the performance I want instead of bringing all records from a table to after filtering, I want to filter them before bringing.

public abstract class BaseRepository<TEntity> where TEntity : class
{
    protected DbContext context;
    protected DbSet<TEntity> dbSet;

    public BaseRepository(DbContext context)
    {
        this.context = context;
        this.dbSet = context.Set<TEntity>();
    }

    public virtual IEnumerable<TEntity> GetAll()
    {
        return this.dbSet.AsQueryable();
    }
}

public class MovimentoTratamentoRepo : BaseRepository<MovimentoTratamento>
{
    public MovimentoTratamentoRepo() : base(new PegasusOdsContext()) { }

    public IQueryable<MovimentoTratamento> GetMovimentoTratamento()
    {
        return context.Set<MovimentoTratamento>(); 
    }
}

And then call it like this:

GetMovimentoTratamento().Where(x=>x.nome == nome).ToList();

or

GetAll().Where(x=>x.nome == nome).ToList();

Is there a difference between the two methods? Is this the best way to do this?

    
asked by anonymous 14.03.2016 / 12:18

1 answer

1

SQL Server Profiler

It is normal to have this kind of doubt with EF or any other ORM tool. To make it easier to analyze, it would be interesting to use SQL Profiler . This tool can intercept all the queries that are being sent to the bank.

  • What is SQL Server Profiler

link

  • Starting SQL Server Profiler

link

Concept of execution in EF

The EF will only execute the query after executing the command ToList() , follow link.

  • Understanding the execution cycle in EF

link

Sending filters to the repository

To make it easy to run filters, you can send Func<T,bool> to your repository. See the code.

public abstract class BaseRepository<TEntity> where TEntity : class
{
    protected DbContext context;
    protected DbSet<TEntity> dbSet;

    public BaseRepository(DbContext context)
    {
        this.context = context;
        this.dbSet = context.Set<TEntity>();
    }

    public virtual IEnumerable<TEntity> GetAll()
    {
        return this.dbSet.AsQueryable();
    }

    public virtual IEnumerable<TEntity> GetAll(Func<TEntity, bool> filter)
    {
        return this.dbSet.AsQueryable().Where(filter).ToList();
    }
}

public class MovimentoTratamentoRepo : BaseRepository<MovimentoTratamento>
{
    public MovimentoTratamentoRepo() : base(new PegasusOdsContext()) { }

    public IQueryable<MovimentoTratamento> GetMovimentoTratamento()
    {
        return context.Set<MovimentoTratamento>(); 
    }

    public IEnumerable<MovimentoTratamento> GetMovimentoTratamento(Func<MovimentoTratamento, bool> filter)
    {
        return context.Set<MovimentoTratamento>()
                      .Where(filter)
                      .ToList(); 
    }
}
    
14.03.2016 / 13:24