How to perform a Where using Entity Framework

3

I have a web application that needs to present a list containing some data, for this, I created the Model: Crm_Analise :

public class Crm_Analise
{
    [Key]
    public int id { get; set; }
    public string cod_item_CRM { get; set; }
    public string TAG { get; set; }
    public string data_creat { get; set; }
    public string modelo { get; set; }

    public int cliente_CRM { get; set; }
}

And by Scaffolding I created Controller and Views .

However, I need to display only the data ref. to the customer logged in. So I'm using Session to store the client code.

Then in Controller I did the following:

    public async Task<ActionResult> Index()
    {
        if(Session["cod_cli"] != null)
        {
            db.Crm_Analise.Where(x => x.cliente_CRM == Convert.ToInt32(Session["cod_cli"]));

            return View(await db.Crm_Analise.ToListAsync());
        }
        else
        {
            return Error();
        }
    }

However, it has not changed at all, it keeps bringing me the whole list.

    
asked by anonymous 12.07.2017 / 21:02

2 answers

5

Missing the filtered query in ToListAsync() .

Note that Where does not change the original collection, regardless of whether it is a list, a IQueryable or something else, it returns a new collection with elements that match the predicate

When you return to view using db.Crm_Analise.ToListAsync() you are simply materializing all items from DbSet and sending to view .

public async Task<ActionResult> Index()
{
    if(Session["cod_cli"] != null)
    {
        var query = db.Crm_Analise.
                       Where(x => x.cliente_CRM == Convert.ToInt32(Session["cod_cli"]));

        return View(await query.ToListAsync());
    }
    else
    {
        return Error();
    }
}
    
12.07.2017 / 21:27
5

The problem is that you are running Where, but you run ToListAsync throughout the DbSet, change your code to:

public async Task<ActionResult> Index()
{
    if(Session["cod_cli"] != null)
    {
        return View(await db.Crm_Analise.Where(x => x.cliente_CRM == Convert.ToInt32(Session["cod_cli"])).ToListAsync());
    }
    else
    {
        return Error();
    }
}
    
12.07.2017 / 21:26