c# - EF Core - 根据字段值添加条件
问题描述
我想根据字段 (dateType) 的值向我的查询添加额外的 where 子句
- if dateType = 1 then (StartDate <= Now && EndDate => Now) //具体日期范围
- if dateType = 2 then (Period => Now.Month && Year =>Now.Year) //月
- if dateType = 3 then (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
解决方案
最终答案感谢 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
推荐阅读
- android - Android - 添加 facebook sdk 后 appcompat-v7:27.1.1 错误
- python - python:仅覆盖 AbstractClass 中的一些方法
- java - 在 Spring Boot 中的另一个项目的 application.properties 中替换 @variables@
- angular - 绑定到 [value] 不会更新 FormControl 的值
- html - 通过flexbox或grid使用CSS定位将交替项目与容器中的不同位置对齐?
- angular - 使用复选框删除所选项目
- entity-framework - EF Core 2.1 更新相关实体查询效率
- forms - 如何在 Symfony 4 中总结表单扩展?
- ionic-framework - 错误:模板解析错误:在 Ionic 3 中
- node.js - 异步读取 csv 文件 - NodeJS