我不是一个LINQ程序员,所以这让我感到困惑。我有两个表:首先是带有StartDate和EndDate的计划,加上ID;其次,具有InstanceDate和ScheduleID的ScheduleInstance表。对于Schedule.StartDate和Schedule.EndDate之间的每一天,我需要创建一个ScheduleInstance行 - 但是,仅提前24小时。由于在24小时内创建和删除计划,我必须每隔n分钟生成一个检查程序,以检查ScheduleID的ScheduleInstance是否存在于该24小时窗口内。
型号:
public class Schedule
{
public int ID { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
}
public class ScheduleInstance
{
public int ID { get; set; }
public int ScheduleID { get; set; }
public DateTime InstanceDate { get; set; }
}
LINQ的开头:
var skeds = from sked in context.Schedules
join instance in context.ScheduleInstances
on sked.ID equals instance.ScheduleID
where ((sked.StartDate <= DateTime.Now) && (sked.EndDate >= DateTime.Now))
select sked.ID;
(显然错了)
总而言之,我需要获取Schedule.ID列表,其中ScheduleInstance.InstanceDate中的ScheduleInstance在接下来的24小时内不存在。
非常感谢您的帮助。
更新
DateTime tomorrow = DateTime.Now.AddDays(1);
var skeds = from sked in context.Schedules
join instance in context.ScheduleInstances
on sked.ID equals instance.ScheduleID into g
where (sked.StartDate <= tomorrow) &&
(sked.EndDate >= tomorrow) &&
!g.Any()
select sked;
现在这样可以创建一个实例(在后续代码中,这里不相关),如果明天不存在。如果我将StartDate设置为Now + 2mins,那么在2分钟之后创建Schedule也是完美的。但是,如果我24小时推进时钟,我应该得到一大堆新实例。重申一下,如果现在是一个计划开始日期,结束日期是30天之后,那么我最终应该有31个实例,每个新实例都会提前24小时创建。
答案 0 :(得分:1)
我相信这会解决问题
var today = DateTime.Now;
var nextDay = today.AddDays(1);
var scheds = from sched in context.Schedules
join instance in context.ScheduleInstances
on sched.ID equals instance.ScheduleID into schedInstances
where (sched.StartDate >= today) &&
(sched.EndDate <= nextDay) &&
!schedInstances.Any()
select sched.ID;
答案 1 :(得分:1)
所以你想要在日程表的StartDate和明天之间每天少于一个实例的日程安排?以下是如何实现这一目标的粗略概念:
DateTime tomorrow = DateTime.Now.AddDays(1);
var skeds = from sked in context.Schedules
join instance in context.ScheduleInstances
on sked.ID equals instance.ScheduleID into g
let instances = g.Where(x => x.InstanceDate >= sked.StartDate &&
x.InstanceDate <= tomorrow)
where (sked.StartDate <= tomorrow) &&
(sked.EndDate >= tomorrow) &&
(instances.Count() < (tomorrow - sked.StartDate).Days)
select sked;
答案 2 :(得分:0)
试试这个:(未经测试)
var skeds = from sked in context.Schedules
from instance in context.ScheduleInstances
where (sked.ID == instance.ScheduleID) && ((sked.StartDate <= DateTime.Now) && sked.EndDate >= DateTime.Now))
select sked.ID;
答案 3 :(得分:0)
一方面我应该采用KISS原则。另一方面,我有三个查询而不是一个。但它有效!
var instances = from inst in context.ScheduleInstances
where (inst.StartDateTime >= DateTime.Now)
&& (inst.StartDateTime < tomorrow)
select inst;
var skeds = from sked in context.Schedules
where (sked.StartDate <= DateTime.Now)
&& (sked.EndDate >= tomorrow)
select sked;
var none = from sked in skeds
join inst in instances
on sked.ID equals inst.ScheduleID
into tg
from tcheck in tg.DefaultIfEmpty()
where tcheck == null
select sked;