LINQ中的日期范围重叠问题 [英] Date range overlap issue in LINQ

查看:101
本文介绍了LINQ中的日期范围重叠问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出表中特定记录的日期范围,例如特定领域的名称"

Given date range in Table for particular record say for particular feild "Name"

如果有人试图在上一个日期范围内插入该名称,则不应允许该名称.

If some one trying to insert that Name within previous date range interval then it should not be allowed.

我在这里尝试过一些代码来查看这个……

I have tried here some code look at this ...

if (dataContext.TableAs.Where(
    x => x.EndDate > StartDate &&
    x.Name == Name).Count() == 0)
{
    //insert record
}

但并非总是成功.

有人可以建议我在这里遗漏了什么吗?

Can anyone suggest what I have missing over here ?

我已经在SQL中尝试了以下查询,如何在LINQ中将其用于上述代码

I have tried below query in SQL , how can I use that in LINQ for above code

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'

推荐答案

尝试一下;

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();

这篇关于LINQ中的日期范围重叠问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆