Question

I have been working for hours to get something done that would take me about a minute with TSQL. When I add the join statement to this method VS complains about an ambiguous invocation. When I mouse over ".Where" the pop-up hint runs across one monitor into another, so it's hard for me to extract anything very helpful from it. If I comment out the .Join clause everything is happy.

Thanks for any guidance.

        public List<CategoryDto> Categories(int departmentId)
    {
        IQueryable<CategoryDto> categories = null;
        List<CategoryDto> categoriesList = null;
        using (var context = new ApplicationDbContext())
        {
            categories = context.Categories
                .Join(context.CategoryImages, j => j.CategoryId, c => c.CategoryId,
                    (j, c) => new { CategoryImages = j, Categories = c })
                .Where(c => c.DepartmentId == departmentId)
                .OrderBy(c => c.Name)
                .Select(category => new CategoryDto
                {
                    CategoryId = category.CategoryId,
                    DepartmentId = category.DepartmentId,
                    Name = category.Name,
                    Description = category.Description,
                    DisplayOrderRank = category.DisplayOrderRank,
                    IsActive = category.IsActive
                });
            if (categories != null) categoriesList = categories.ToList();
        }
        return categoriesList;
    }
Was it helpful?

Solution

By using...

.Join(context.CategoryImages, j => j.CategoryId, c => c.CategoryId,
                (j, c) => new { CategoryImages = j, Categories = c })

... you create an IQueryable<T> where T is an anonymous type having two properties, CategoryImages and Categories (although you've got them in the wrong order, and also it's better to use singular words). So you have to continue the LINQ statement by using this anonymous type, like ...

.Where(x => x.Categories.DepartmentId == departmentId)

As said in the comment, with joins comprehensive syntax is way easier:

from c in context.Categories
join i in context.CategoryImages on c.CategoryId equals i.CategoryId
where c.DepartmentId == departmentId // now this is OK

But even better is not to write a join at all and use navigation properties, like Category.Images. By the way, I'm not sure why you're accessing Images, because you don't use them in the end result. Currently the only effect of the join is that you may get non-unique categories.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top