EF Core - add conditional where based on field value

c# entity-framework entity-framework-core linq

Question

I would like to add additional where clauses to my query based on the value of a of a field (dateType)

  • if dateType = 1 then (StartDate <= Now && EndDate => Now) //specific date range
  • if dateType = 2 then (Period => Now.Month && Year =>Now.Year) //month
  • if dateType = 3 then (Period => Now.Month /4) //quarter

I tried the ternary operator but that doesnt work, here is the start of my query.

        var query = from e in context.Events
            join c in context.EventCategories on e.CategoryId equals c.CategoryId
            join o in context.Owners on e.OwnerId equals o.OwnerId
            where !e.IsDeleted 
                  && (e.DateType == 1 ? (e.StartDateTimeUtc <= DateTime.UtcNow && e.EndDateTimeUtc =>DateTime.UtcNow))

using EF Core 2.2

1
0
12/31/2018 1:48:55 PM

Popular Answer

Final answer thanks to Gert Arnold providing direction in comments to OP

    var query = from e in context.Events
                    join c in context.EventCategories on e.CategoryId equals c.CategoryId
                    join o in context.Owners on e.OwnerId equals o.OwnerId
                    where !e.IsDeleted && (e.DateType == 1 && e.StartDateTimeUtc <= DateTime.UtcNow && e.EndDateTimeUtc >= DateTime.UtcNow) //specific date
                                           || (e.DateType == 2 && e.Period >= DateTime.UtcNow.Month && e.Year >= DateTime.UtcNow.Year) // month
                                           || (e.DateType == 3 && e.Period >= DateTime.UtcNow.Month / 3 && e.Year >= DateTime.UtcNow.Year) //quarter
1
12/31/2018 2:12:43 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow