给出特定记录表中的日期范围,例如特定字段“名称”
如果有人试图在之前的日期范围间隔内插入该名称,则不应该允许它。
我在这里试过一些代码看看这个......
if (dataContext.TableAs.Where(
x => x.EndDate > StartDate &&
x.Name == Name).Count() == 0)
{
//insert record
}
但不是一直都没有成功。
有人能建议我在这里失踪吗?
我在SQL中尝试了下面的查询,如何在LINQ中使用它来代替上面的代码
SELECT COUNT(*) FROM TableA WHERE ('2012-04-02' between StartDate and EndDate or '2012-08-28'
between StartDate and EndDate or StartDate between '2012-04-02' and '2012-08-28' or EndDatebetween '2012-04-02' and '2012-08-28' ) and Name='Test'
答案 0 :(得分:3)
试试这个;
if (dataContext.TableAs
.Where(x => x.Name == Name)
.Max(x => x.EndDate) < StartDate)
编辑 - 问题的第二部分
DateTime Date1 = new DateTime("2012-04-02");
DateTime Date2 = new DateTime("2012-08-28");
var query = (dataContext.TableAs
.Where(x => x.Name == "Test")
.Where(x => (x.StartDate >= Date1 && Date1 <= x.EndDate)
|| (x.StartDate >= Date2 && Date2 <= x.EndDate)
|| (Date1 >= x.StartDate && x.StartDate <= Date2)
|| (Date1 >= x.EndDate && x.EndDate <= Date2))).Count();
答案 1 :(得分:0)
var StartDate = new DateTime(2012,04,02);
var EndDate = new DateTime(2012,08,28);
var Name = "Test";
if (!dataContext.TableAs.Any(
x=> x.Name == Name && x.EndDate >= StartDate && x.StartDate <= EndDate
)
{
//insert record
}