[英]Only include in where condition if date is not low date(01/01/0001)
I have a query that has a where condition to check and find addresses that were added after a certain date.我有一个查询,它有一个 where 条件来检查和查找在某个日期之后添加的地址。 The date field is not required so I want Date field in where condition to be only considered if it is not 1/1/0001.
日期字段不是必需的,因此我希望仅在不是 1/1/0001 时才考虑条件的日期字段。 dtmDate is the parameter that is being passed
dtmDate 是正在传递的参数
Query询问
from b in _context.customer
join d in _context.Address on b.id equals d.Id
join e in _context.units on d.Id equals e.Id
where (req.dtmDate.Year != 1 && d.DateAdded >= req.dtmDate)
select new modelAddress
{
address= d.address
}
But this is not working.但这不起作用。 It is not returning any rows
它没有返回任何行
I'd leverage the fact that LINQ queries are not executed when you write them, so you can add clauses conditionally after you've created a base query:我会利用 LINQ 查询在编写时不执行的事实,因此您可以在创建基本查询后有条件地添加子句:
var query = from b in _context.customer
join d in _context.Address on b.id equals d.Id
join e in _context.units on d.Id equals e.Id;
if(req.dtmDate.Year != 1)
query = query.Where(d.DateAdded >= req.dtmDate);
var result = query.Select(
new modelAddress
{
address= d.address
}
);
I prefer this because I've previously run into issues, particularly with EF LINQ queries when the Where clause contains something that evaluates to true locally with in the code, rather than as something the DB will evaluate.我更喜欢这个,因为我以前遇到过问题,特别是在 EF LINQ 查询时 Where 子句包含在代码中本地评估为 true 的内容,而不是数据库将评估的内容。 It seems to work out better when "wildcarding" DB queries, to use a pattern of "if x is true then add-another-where-clause" rather than saying "where(local-value-of-x-equals-local-constant OR some-db-data-value-equals-y)"
在“通配符”数据库查询时,使用“如果 x 为真,则添加-另一个-where-clause”而不是“where(local-value-of-x-equals-local-”的模式似乎效果更好常量或一些-db-data-value-equals-y)"
If I understand you correctly, you have a DateTime
object called req.dtmDate
that may be set to a default value, and you want to return all items where the item's DateAdded
field is greater than req.dtmDate
, unless req.dtmDate
is 1/1/0001
, in which case all records should be returned.如果我理解正确,您有一个名为
req.dtmDate
的DateTime
object 可能设置为默认值,并且您希望返回项目的DateAdded
字段大于req.dtmDate
的所有项目,除非req.dtmDate
是1/1/0001
,在这种情况下应返回所有记录。
If that's the case, I think you could just modify your existing code to:如果是这种情况,我认为您可以将现有代码修改为:
where (req.dtmDate.Year == 1 || d.DateAdded >= req.dtmDate)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.