Reputation: 9487
I want to get the users based on the continent for my application. I used the following code for this. Now I want to show all users if the continentId is null. How can I achieve this?
public async Task<IEnumerable<User>> GetUsersByContinent(int? continentId)
{
var users = await _context.Users
.Include(u => u.Country).ThenInclude(c => c.Continent)
.Where(u => u.Country.ContinentId == continentId)
.OrderBy(u => u.Username)
.ToListAsync();
return users;
}
Upvotes: 1
Views: 50
Reputation: 12196
I would probably use @Jehof solution, but it's worth mentioning alternative solution.
.Where(u => continentId == null || u.Country.ContinentId == continentId)
Upvotes: 1
Reputation: 35554
You can use use method chaining to solve your problem.
public async Task<IEnumerable<User>> GetUsersByContinent(int? continentId)
{
var baseQuery= _context.Users.Include(u => u.Country).ThenInclude(c => c.Continent);
if (continentId.HasValue){
baseQuery = baseQuery.Where(u => u.Country.ContinentId == continentId)
}
return await baseQuery.OrderBy(u => u.Username).ToListAsync();
}
Upvotes: 1