EF Core-根据字段值添加条件

时间:2018-12-31 13:38:21

标签: c# entity-framework linq entity-framework-core

我想根据字段(dateType)的a值向查询中添加其他where子句

  • 如果dateType = 1,则(StartDate <= Now && EndDate => Now)//特定日期范围
  • 如果dateType = 2,则(时段=> Now.Month && Year => Now.Year)//月
  • 如果dateType = 3,那么(Period => Now.Month / 4)//季度

我尝试了三元运算符,但这不起作用,这是我查询的开始。

        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))

使用EF Core 2.2

1 个答案:

答案 0 :(得分:1)

最后的答案,感谢Gert Arnold在对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