LINQ检查行是否落在没有间隙的日期之间

时间:2014-01-09 02:41:34

标签: c# sql linq

我需要编写一个查询,如果日期介于开始日期和结束日期之间,它只返回行而没有间隙。

下面会失败并且什么都不返回:

Requested -----[---------------------------------]--------
In the DB ----------------[------]------------------------

Requested -----[---------------------------------]--------
In the DB --[----------------]----------------------------

Requested -----[---------------------------------]--------
In the DB --[----------------]---------[----------------->

下面将传递并返回数据库中的行:

Requested -----[---------------------------------]--------
In the DB -----[---------------------------------]--------

Requested -----[---------------------------------]--------
In the DB --[------------------------------------------]--

Requested -----[---------------------------------]--------
In the DB --[----------------][---------------][--------]-

修改

这是表格外观的POCO对象:

public class SubscriptionPeriod
{    
    public int Id { get; set; }
    public int SubscriptionId { get; set; }
    public int? MatchedSubscriptionPeriodId { get; set; }
    public SubscriptionPeriodStatuses Status { get; set; }
    public int Qty { get; set; }
    public int? FillQty { get; set; }
    public DateTime SubscriptionStartDate { get; set; }
    public DateTime? SubscriptionEndDate { get; set; }
    public int? RenewQty { get; set; }
    public bool RollOverQty { get; set; }
    public DateTime? ProcessedDate { get; set; }
    public DateTime CreateDate { get; set; }
}

SubscriptionPeriods
    .Where(sp => sp.Subscription.UserId == userId && 
        sp.Subscription.ZoneId == zoneId && 
        sp.Subscription.Type == 2 && 
        sp.MatchedSubscriptionPeriodId == null && 
        sp.SubscriptionStartDate <= subscriptionEndDate &&
        sp.SubscriptionEndDate >= subscriptionStartDate &&
        (sp.Status == SubscriptionPeriodStatuses.Initalized || sp.Status == SubscriptionPeriodStatuses.Open))
    .Sum(s => (int?)s.Qty)

注意:当SubscriptionEndDate为null时,表示订阅会从开始日期开始。

0 个答案:

没有答案