Search code examples
c#linqlambdamany-to-manyentity

adding where clauses to a many many relationship


I want to build a directory for restaurant, the search is based in three condition the problem that I have is add the third where clause that uses typecuisine like you see in code the 2 first conditions are good my entity

var query = db.Restaurants.AsQueryable();

if (!string.IsNullOrEmpty(Name))
    query = query.Where(c => c.Nom.Contains(Name));

if (RegionId != Guid.Empty)
    query = query.Where(c => c.RegionId == RegionId);

//how to get typecuisine ID from table Restaurant instead it's only in  table TypeCuisine


if (typeId != Guid.Empty)
    query = query.Where(tc=> tc.TypeCuisines.Where(r=>r.TypeCuisineId == typeId));

return query.ToList();

Solution

  • The .Where is expecting a return type of bool and you are returning the results of an inner Where, meaning an IEnumerable.

    What you are missing is the .Any() function instead of the inner Where.

    var query = db.Restaurants.AsQueryable();
    
    if (!string.IsNullOrEmpty(Name))
        query = query.Where(c => c.Nom.Contains(Name));
    
    if (RegionId != Guid.Empty)
        query = query.Where(c => c.RegionId == RegionId);
    
    if (typeId != Guid.Empty)
        query = query.Where(tc=> tc.TypeCuisines.Any(r => r.TypeCuisineId == typeId));
    
    return query.ToList();