0

I am building a gaming website where Games have collection of Categories

public class Game
    {

        public int Id { get; set; }

        public string Name { get; set; }

        public virtual ICollection<CategoryMain> categoryMain { get; set; }

    }

I want to find list of Games by choosing 1 category from the list of categories.

var games= await db.Games.Include(u => u.applicationUser)
                                        .Include(c => c.categoryMain)
                                        .Where(c => c.categoryMain.Id == x) // <-- My Issue Here
                                        .ToListAsync();

Because "categoryMain" is a collection, I cannot access it's properties "Id" to filter games by category.

Previously I had Games have 1 category only, things works fine, but now I want to have the ability for games to have multiple categories, so I really need this.

Thanks

1 Answer 1

3

You should be able to get the desired result using the .Any() method.

var games = await db.Games
                    .Include(x => x.categoryMain)
                    .Where(x => x.categoryMain.Any(y => y == categoryId)
                    .ToListAsync();

Personally, I always find it's easier to reverse the query if you're doing something like this because I find it improves readability.

Something like this:

var games = await db.CategoryMain
                    .Include(x => x.Game)
                    .Where(x => x.Id == categoryId)
                    .Select(x => x.Game)
                    .ToListAsync();
Sign up to request clarification or add additional context in comments.

1 Comment

It worked, thank you for your swift help, I appreciate it a lot !

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.