Dynamic filters using lambda

0

I have a table

  

ErrorsProduction_Registros

that links to another table called

  

ErrorsProducao_Tipos.

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

If I run 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 of the data in the ErrorsProduction_Types table for the database relationship, however, I have some questions about 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();
}

But this last demonstrated way, I no longer have access to the object of the ErrorsProducao_Tipos table.

How do I proceed?

    
asked by anonymous 13.09.2016 / 22:34

1 answer

1

As for perfomance, continue to use IQueryable , because this will certainly be faster than the first example because the filter will be done in the data bank, while in the first it will be done in memory with all records already removed from the database. data.

Just use Include . Add using System.Data.Entity because it has an Include method in another namespace, in 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 annoying to understand, but Include will fix it.

link

    
14.09.2016 / 00:59