我有以下查询可以正常工作。但是,它不适用于需要它的连接查询。
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
});
}
因此,我一直试图在条件(something like this answer by Whaheed)没有运气的情况下嵌入其他内容。
任何帮助都将不胜感激。
答案 0 :(得分:4)
您可以将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块。你仍然可以 这样做,但这有点痛苦。
答案 1 :(得分:1)
您无法将new { LogDate, c.Rain_today }
强制转换为Wxlog
,您需要从这两个查询中返回select c
。
如果您只想在最后else
之后选择该部分,请输入以下内容
var ra2 = from r in ra
select new {
LogDate,
c.Rain_today
};
答案 2 :(得分:1)
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();
}