[英]LINQ to Entities conditional where clause
我有以下查询,可以正常工作。 但是,它在需要它的联接查询中不起作用。
var ra = from c in _context.Wxlogs
select c;
if (year == "2011")
{
ra = (IQueryable<Wxlog>)(from c in _context.Wxlogs
where c.LogYear == year
&& (SqlFunctions.DatePart("Month", c.LogDate2) == m3)
&& c.LogTime.Contains("23:59")
orderby c.LogDate2
let LogDate = c.LogDate2
select new {
LogDate,
c.Rain_today
});
}
else if (year != "2011")
{
ra = (IQueryable<Wxlog>)(from c in _context.Wxlogs
where c.LogYear == year
&& c.LogMonth == mm
&& c.LogTime.Contains("08:59")
orderby c.LogDate2
let LogDate = EntityFunctions.AddDays(c.LogDate2, -1)
select new {
LogDate,
c.Rain_today
});
}
因此,我一直在尝试在条件不佳的情况下嵌入else if条件( 类似Whaheed的回答 )。
任何帮助,将不胜感激。
您可以将var
与条件运算符配合使用:
var query = year == "2011" ?
from c in _context.Wxlogs
where c.LogYear == year
&& (SqlFunctions.DatePart("Month", c.LogDate2) == m3)
&& c.LogTime.Contains("23:59")
orderby c.LogDate2
let LogDate = c.LogDate2
select new {
LogDate,
c.Rain_today
});
// Second part of conditional
: from c in _context.Wxlogs
where c.LogYear == year
&& c.LogMonth == mm
&& c.LogTime.Contains("08:59")
orderby c.LogDate2
let LogDate = EntityFunctions.AddDays(c.LogDate2, -1)
select new {
LogDate,
c.Rain_today
});
这并不理想,但是由于您还要根据年份更改“ LogDate”位,因此这可能是最简单的方法-两个查询在太多地方存在差异,无法以常规方式提取。 (这并不像标题中所示实际上只是有条件的“ where”子句。)
这里需要var
的原因是因为您要投影为匿名类型。 如果您不这样做,则可以使用if / else块。 您仍然可以通过其他方式来做到这一点,但这有点痛苦。
您不能将new { LogDate, c.Rain_today }
为Wxlog
,而需要从两个查询中返回select c
。
如果您只想选择该部分,则可以在else
部分之后键入以下内容
var ra2 = from r in ra
select new {
LogDate,
c.Rain_today
};
试试(评论后编辑):
if (year == "2011")
{
ra = (from c in _context.Wxlogs
where c.LogYear == year &&
&& (SqlFunctions.DatePart("Month", c.LogDate2) == m3)
&& c.LogTime.Contains("23:59")
orderby c.LogDate2
let LogDate = EntityFunctions.AddDays(c.LogDate2, year == "2011" ? 0 : -1)
select new {
LogDate,
c.Rain_today
}).AsQueryable();
}
else if (year != "2011")
{
ra = (from c in _context.Wxlogs
where c.LogYear == year &&
&& c.LogMonth == mm
&& c.LogTime.Contains("08:59")
orderby c.LogDate2
let LogDate = EntityFunctions.AddDays(c.LogDate2, year == "2011" ? 0 : -1)
select new {
LogDate,
c.Rain_today
}).AsQueryable();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.