0

I need to filter only the visibles products from a category, but it's not working.

Category category = db.Categories
            .Include(c => c.Products.Where(p => p.IsVisible))
            .First(c => c.CategoryID == id);

Error:

The Include path expression must refer to a navigation property defined on the type. Use dotted paths for reference navigation properties and the Select operator for collection navigation properties.

UPDATE

 var result = (from c in db.Categories
                             where c.CategoryID == id
                             select new
                             {
                                 CategoryID = c.CategoryID,
                                 Description = c.Description,
                                 Products = (from p in db.Products
                                             where p.IsVisible
                                             && p.CategoryID == c.CategoryID
                                             orderby p.DateSent descending
                                             select p)
                             }).FirstOrDefault();

but now i need to cast the anonymousType to Category

1

2 Answers 2

1

Your query doesn't make sense if you want:

the visibles products from a category

If you genuinely want the visible products, try this:

var visibleProducts = db.Categories
                        .Where(c => c.CategoryID == id)
                        .Select(c => c.Products.Where(p => p.IsVisible));

Note: untested

Sign up to request clarification or add additional context in comments.

4 Comments

i'll test, but i need the category data plus a list of visible products
You already have the id of the category, you could just make it 2 queries. First query gets the category, second query gets the visible products from the category. That way you have both.
i know that i can use 2 queries, but due performece it would be nice to make it using only 1.
There won't be a performance issue, it already has to do those 2 queries anyway. Might as well just store the results from both separately.
0

Maybe something like:

var category = db.Products.Where(p=>p.IsVisible && p.CategoryID == id).Include("Category").ToList().Select( p=> p.Category).Distinct();

It may not be ideal because of the ToList... but I can see no other way right now.

Maybe you could change the Distinct into a FirstOrDefault()...

var category = db.Products.Where(p=>p.IsVisible && p.CategoryID == id).Include("Category").ToList().FirstOrDefault().Category;

Not tested either...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.