如何验证数据库中未占用的日期
本文关键字:未占用 日期 数据库 何验证 验证 | 更新日期: 2023-09-27 18:18:45
我想检查日期范围落在我提供的日期或不。例如,我有一个包含"FROM
"answers"TO
"日期的表。
我只是想检查给定的日期不属于数据库中的日期。
数据库中的数据
FromDate and TODate
1 Aug 2012 ------ 4 Aug 2012
5 Aug 2012 ------ 11 Aug 2012
12 Aug 2012 ------ 15 Aug 2012
From and To Dates示例
FromDate and ToDate
1 Aug 2012 ------ 2 Aug 2012 **Should Return INVALID**
5 Aug 2012 ------ 11 Aug 2012 **Should Return INVALID**
10 Aug 2012 ------ 10 Aug 2012 **Should Return VALID**
15 Aug 2012 ------ 15 Aug 2012 **Should Return INVALID**
有人能给点主意吗?
我使用LINQ
到SQL
从数据库查询。
编辑:只是想确保我的to和From日期不与数据库中的日期冲突
间隔的开始和结束点是正确的,不检查它。我们检验现有区间是否与所讨论的区间相交:
void Main()
{
var ExistIntervals = new HashSet<Interval>();
//1 Aug 2012 4 Aug 2012
//5 Aug 2012 11 Aug 2012
//12 Aug 2012 15 Aug 2012
ExistIntervals.Add(new Interval { From = new DateTime(2012, 8, 1),
To = new DateTime(2012, 8, 4) });
ExistIntervals.Add(new Interval { From = new DateTime(2012, 8, 5),
To = new DateTime(2012, 8, 11) });
ExistIntervals.Add(new Interval { From = new DateTime(2012, 8, 12),
To = new DateTime(2012, 8, 15) });
var QueryIntervals = new HashSet<Interval>();
//1 Aug 2012 2 Aug 2012 INVALID
//5 Aug 2012 11 Aug 2012 INVALID
//10 Aug 2012 10 Aug 2012 VALID
//15 Aug 2012 15 Aug 2012 INVALID
QueryIntervals.Add(new Interval { From = new DateTime(2012, 8, 1),
To = new DateTime(2012, 8, 2) });
QueryIntervals.Add(new Interval { From = new DateTime(2012, 8, 5),
To = new DateTime(2012, 8, 11) });
QueryIntervals.Add(new Interval { From = new DateTime(2012, 8, 10),
To = new DateTime(2012, 8, 10) });
QueryIntervals.Add(new Interval { From = new DateTime(2012, 8, 15),
To = new DateTime(2012, 8, 15) });
var result = QueryIntervals.Where( x=> !ExistIntervals.Any(
y=>(y.From <= x.From && x.From <= y.To)
|| (y.From <= x.To && x.To<=y.To)
)
);
result.Dump();
}
public class Interval
{
public DateTime From { get; set; }
public DateTime To { get; set; }
}
结果为空集合。
(结果为空集,自2012年8月10日起:5 Aug 2012 ------ 2012年8月11日)
你可以用LinqPad测试。
:
假设表名为"CompaitnDates",上下文名为"CompaitnContext",并确定两个变量的间隔:"checkFrom","checkTo"。
var checkFrom = new DateTime(2012, 8, 10);
var checkTo = new DateTime(2012, 8, 10);
var db = new CompaitnContext();
则测试可如下:
var isValid = !db.CompaitnDates.Any(
y=>(y.From <= checkFrom && checkFrom <= y.To)
|| (y.From <= checkTo && checkTo<=y.To)
);