检查一个日期时下降日期范围-Linq查询之间(Check One Date is falling B

2019-10-21 17:35发布

我正在存储database.From和结束日期将被存储在DB.I雇员的休假信息要阻止员工休假申请,当谈到在已应用范围的叶子。

例如:假设2015年1月1日之间的一个员工已经申请准予2015年5月1日,

i)if user again try to apply leave for 04/01/2015 to 07/01/2015,then i  need to block that one.
ii)if user again try to apply leave for 05/01/2015 to 05/01/2015,then i  need to block that one.

我如何才能找到它使用LINQ查询

Answer 1:

试试这个:

var startDate = new DateTime(2015, 01, 04);
var endDate = new DateTime(2015, 01, 07);
if (_context.AppliedLeaves.Any(x => 
     x.UserId == userId &&
     ((startDate >= x.StartDate && startDate <= x.EndDate) || 
      (endDate >= x.StartDate && endDate <= x.EndDate)))
{
    throw Exception("You cannot apply this period");
}


Answer 2:

你可以尝试如下

    return (from t1 in db.Employee where ( empid == t1.EmplyeeId &&
date1 >= t1.LeaveStart && date2 <= t1.LeaveEnd))

你可以按照以下尝试,详细的解答

int cntleaves = (from values in dbcontext.User_master
                       where values.iUser_id == Userid &&
                               ((values.dtStart_date >= Startdate &&
                                values.dtEnd_date <= Enddate)
                                 ||
                                 (values.dtStart_date <= Startdate &&
                                values.dtEnd_date <= Enddate))
                       select values).ToList().Count();

        if (cntleaves > 0) {
            ViewBag.Message = "You have already applied for leaves !";            
        }


Answer 3:

另一种更好的方法是创建一个扩展方法来DateTime类为:

public static bool Between(this DateTime input, DateTime date1, DateTime date2)
{
    return (input > date1 && input < date2);
}

然后你可以使用LINQ谓词where子句中使用。

如果(leaves.Where(L => l.empId == EMPID && dateApplied.Between(属植物,l.to))。在任何()){...错误...}

PS:这是你的方向只是伪代码。



Answer 4:

IF EXISTS (
SELECT * FROM table WHERE user = @user AND (
@newStartDate BETWEEN appliedStartDate AND appliedEndDate

)
PRINT 'Can not apply'
ELSE PRINT 'Can apply'


文章来源: Check One Date is falling Between Date Range-Linq query