Filter per parameter or all

1

I query the database using linq.

I would like to filter the ID_LEAD column by the value of the filter "if there is an int (filter.code) or filter all over the world.

Follow the example of how the procedure is in the bank

WHERE ---- @ID_LEAD ----
LE.ID_LEAD = ISNULL(@ID_LEAD,ID_LEAD)

I would like to do this in my query

var lead = (from l in this.DB.BGC_LEAD
                                  where l.ID_LEAD == ).ToList();
    
asked by anonymous 17.04.2017 / 21:52

3 answers

1

Just check if there is a value in the variable that holds the filter and work on a Boolean expression.

Example

If it is nullable and null it represents the absence of a parameter (that is, return all records):

var lead = (from l in this.DB.BGC_LEAD
            where filtro.codigo == null || l.ID_LEAD == filtro.codigo.Value)
            .ToList();

If it is a% of normal% and 0 represents the absence of a parameter:

var lead = (from l in this.DB.BGC_LEAD
            where filtro.codigo == 0 || l.ID_LEAD == filtro.codigo)
            .ToList();
    
17.04.2017 / 21:57
2

It would be this:

var leadId = 0;

if(parametro == 1)
 leadId = 1
else
 leadId = 2;

var lead = (from l in this.DB.BGC_LEAD
                                  where l.ID_LEAD ==leadId).ToList();
    
17.04.2017 / 21:58
1

First, in your SQL query you should do this:

WHERE LE.ID_LEAD = 0 OR ID_LEAD = @ID_LEAD

In LINQ in the same way:

//pId é seu parâmetro (não nulo)
var lead = (from l in this.DB.BGC_LEAD
            where l.ID_LEAD == pId || pId == 0).ToList();

If you pass as a parameter the value zero, then it will be true for all occurrences, if you pass something, you will only consider the ID_LEAD equal to the parameter.

    
17.04.2017 / 22:03