Dynamic filters using lambda

Asked

Viewed 272 times

0

I have a table

Errosproducao_records

linked to another table called

Errosproducao_tipos.

I need to perform dynamic filters in the table Errors_records using lambda expressions.

if I perform the filters like this:

List<ErrosProducao_Registros> list = db.ErrosProducao_Registros.ToList();

//filtra o tipo de erro
if (codTipoErro >= 0)
    list = list.Where(e => e.CodTipoErro == codTipoErro);

my variable list still has all the data from the table Errosproducao_types by the database relation, however, I have doubts about the performance using this method.

Today I do as below:

using (DB_VISTA_RECORTEEntities db = new DB_VISTA_RECORTEEntities())
{
    IQueryable<ErrosProducao_Registros> result = db.ErrosProducao_Registros;

    //filtra o tipo de erro
    if (codTipoErro >= 0)
       result = result.Where(e => e.CodTipoErro == codTipoErro);

    List<ErrosProducao_Registros> list = result.ToList();
}

However, this last demonstrated way I no longer have access to the table object Errosproducao_types.

How should I proceed?

  • 1

    Ever tried to use a Include?, or else in Select get what you need? the Second way is the ideal, because it only brings what you need from your tables!

1 answer

1


How much performance continue using the IQueryable, because this way it will surely be faster than the first example because the filter will be done in the database, while in the first will be done in memory with all records already taken from the database.

Just use the Include. Add using System.Data.Entity because it has a include method in another namespace, in the System.Linq if I’m not mistaken.

using (DB_VISTA_RECORTEEntities db = new DB_VISTA_RECORTEEntities())
{
    IQueryable<ErrosProducao_Registros> result = db.ErrosProducao_Registros.Include(e => e.ErrosProducao_Tipos);

    //filtra o tipo de erro
    if (codTipoErro >= 0)
       result = result.Where(e => e.CodTipoErro == codTipoErro);

    List<ErrosProducao_Registros> list = result.ToList();
}

But you can work with Lazyloading, it’s a bit boring to understand, but Include will already solve.

http://www.entityframeworktutorial.net/EntityFramework4.3/lazy-loading-with-dbcontext.aspx

Browser other questions tagged

You are not signed in. Login or sign up in order to post.