首页 > 解决方案 > EF Core - 根据字段值添加条件

问题描述

我想根据字段 (dateType) 的值向我的查询添加额外的 where 子句

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

        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

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

解决方案


最终答案感谢 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

推荐阅读