Mill3r
Mill3r

Reputation: 544

LINQ query with dynamic parameter and perform Count operation ASP.NET Core 3.1

I am trying to query a table with dynamic filter parameters. The objective is to count the number of rows which matches the filters.

A very simplified version of the controller

   public async Task<IActionResult> Index(string PTypeId = null, string Country = null, string BTypeId = null)
    {
       int countList = await _context.InfoProducts.Where(obj => obj.Status.Equals(100) && ((PTypeId == null || obj.PTypeId == PTypeId) || (BTypeId == null || obj.BTypeId == BTypeId) || (Country == null || obj.Country == Country ))).CountAsync();

    }

Explanation: What I'm trying to do is when a parameter is passed such as PTypeId, BTypeId of Country, it should take that parameter into account and count the number of row according to that. If no parameter is passed then it should return the total number of rows.

Result: I am always getting the total number of rows which has a status of 100. Even if a parameter is passed, it is ignoring it and returning the total number of rows in all cases.

I have even tried hard coding the parameter but it still returns all number of rows which has a status of 100.

How can I get the result.

Upvotes: 1

Views: 472

Answers (1)

Serge
Serge

Reputation: 43931

For some reason I think you should change guery to :

var countList = await _context.InfoProducts
                        .Where(obj => obj.Status.Equals(100)
                        && ((PTypeId == null || obj.PTypeId == PTypeId))
                        && ((BTypeId == null || obj.BTypeId == BTypeId))
                        && ((Country == null || obj.Country == Country))
                        ).CountAsync();

Upvotes: 2

Related Questions