3

给定表格中特定记录的日期范围,例如特定字段“名称”

如果有人试图在以前的日期范围间隔内插入该名称,则不应允许。

我在这里试过一些代码看看这个......

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'
4

2 回答 2

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();
于 2012-08-29T10:12:04.447 回答
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
}
于 2012-08-29T10:50:36.953 回答