This is a migrated thread and some comments may be shown as answers.

Help needed with many-to-many filter

2 Answers 75 Views
LINQ (LINQ specific questions)
This is a migrated thread and some comments may be shown as answers.
This question is locked. New answers and comments are not allowed.
Daniel Plomp
Top achievements
Rank 2
Daniel Plomp asked on 24 Mar 2011, 04:46 PM
Hi all,

I need some help with the following case:

Tables
- Product
- Keyword
- ProductKeyword (only ID's)

Each product can have one or more keywords and vice versa.

So I have a many-to-many solution. What I want is the following:
On my webpage I want to select one or more keywords. When I click 'Search', I need a result of product items which all match the selected keywords.

This is the code based on one keyword:
/// <summary>
        /// Search for products
        /// </summary>
        /// <param name="itemsPerPage"></param>
        /// <returns></returns>
        public List<Product> SearchProducts(int from, int max, List<Keyword> filter, out int totalitems)
        {
            try
            {
                // FILTER ON KEYWORDS
 
                var items = context.Products.Where(x => x.Visible == true);
                totalitems = items.Count();
 
                return items.Where(x => x.Visible == true).Skip(from).Take(max).ToList();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


How can I do this?

Regards,
Daniel 

2 Answers, 1 is accepted

Sort by
0
Daniel Plomp
Top achievements
Rank 2
answered on 28 Mar 2011, 09:09 AM
Well, I've come with the following solution:

// Filter on keywords
var products = from p in context.Products
               from k in p.Keywords
               where filter.Contains(k)
               select p;
 
totalitems = products.Distinct().Count();
return products.Where(x => x.Visible == true).Distinct().Skip(from).Take(max).ToList();

This seems to work. If anyone has a better solution?

Regards,
Daniel
0
Serge
Telerik team
answered on 29 Mar 2011, 05:38 PM
Hello Daniel Plomp,

 First of all I am glad you have found a solution to your problem.  Another solution would be to just use a collection of the identities of the desired keywords and query on that, however your solution looks fine in the current situation. 

If you need further help or face further trouble do not hesitate to let us know.

Greetings,
Serge
the Telerik team
Tags
LINQ (LINQ specific questions)
Asked by
Daniel Plomp
Top achievements
Rank 2
Answers by
Daniel Plomp
Top achievements
Rank 2
Serge
Telerik team
Share this question
or