Home > Mobile >  How to include any enum value in property with Linq where clause
How to include any enum value in property with Linq where clause

Time:11-13

I have this Linq statement below, where calendarParams.RegisteredType is a nullable int. In the second to last line where I set the value to null if there is no value, how can I set it to any (enum) value, if the value is null?

var registrants = await _dbContext.Registrants
    .Where(p => p.EventDate.Month == calendarParams.Date.Month 
        && p.EventDate.Year == calendarParams.Date.Year 
        && p.UserId == userId 
        && (p.RegistrantType == (calendarParams.RegisteredType.HasValue ? (RegistrantType)calendarParams.RegisteredType : null)))
    .ToListAsync();

CodePudding user response:

For my understanding you can not do that inside LinQ as not accept any kind of integrated function or structure. So the more easy way to me is get over the problem outside the LinQ

int? myvalue = calendarParams.RegisteredType.HasValue ? (RegistrantType)calendarParams.RegisteredType : null;

var registrants = await _dbContext.Registrants
    .Where(p => p.EventDate.Month == calendarParams.Date.Month 
        && p.EventDate.Year == calendarParams.Date.Year 
        && p.UserId == userId 
        && p.RegistrantType == myvalue)
    .ToListAsync();

By the way I don't understand what are you doing the "HasValue" check if the default value is null. But I do exactly the same only to show the principle. In this case "int?" is the "int nullable" (I don't know if I understand the type of RegistrantType, but I think you get the idea)

CodePudding user response:

I figured out what I needed to do. Here is my answer.

var query = _dbContext.Registrants
       .Where(p => p.EventDate.Month == calendarParams.Date.Month && p.EventDate.Year == calendarParams.Date.Year && p.UserId == userId)
       .Select(f => f);

        if (calendarParams.RegisteredType.HasValue) {
            query = query.Where(p =>  p.RegistrantType == (RegistrantType)calendarParams.RegisteredType);
        }

        var registrants = await query.ToListAsync();
  • Related