M
M
Michael2017-01-03 02:40:27
ASP.NET
Michael, 2017-01-03 02:40:27

How to fix my LINQ query?

Hello, I am making an online store and trying to implement the "similar products" function, that is, we go into a certain category of products, go into a view with detailed product descriptions and at the bottom we offer products similar to the category, the idea was to use LINQ queries with random output of records by categories from the database table, and output them to the view. See here is one of my requests:

public PartialViewResult Test2()
        {

            ListViewModel model = new ListViewModel
            {
                Furnitures = repository.Furnitures
                .Where(x =>   x.Category.Equals("Кухни"))
                .OrderBy(r => Guid.NewGuid()).Take(1)              
        };
            return PartialView(model);
            
        }

Everything is fine and working here, it displays a random entry from the table in the "Kitchens" category and is displayed on the page. But I can't use such a query, because in all categories I will only display products from the "Kitchen" category. Question: How to display random products from the table depending on the category we are in?? For example, we went to the "beds" category and we got a random list of products from the beds, we went to the Cabinets section, we got a list of random products from the cabinets category. I tried changing this method to this:
public PartialViewResult Test2(string category)
        {

            ListViewModel model = new ListViewModel
            {
                Furnitures = repository.Furnitures
                .Where(x => category == null ||  x.Category == category)
                .OrderBy(r => Guid.NewGuid()).Take(1),

            CurrentCategory = category
            };
            return PartialView(model);
            
        }

But it displays data from all categories, can I somehow remake the request ?? Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
MrDywar Pichugin, 2017-01-03
@M-Misha-M

Do it just like in the first example.
If category is null or an empty string, then there will be no such category or there are goods that do not fall under the category.
You displayed all categories because the condition worked category == null. In the debugger, make sure that the variable is set.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question