我将员工的休假信息存储在数据库中。从和日期将存储在DB中。我想阻止员工申请休假,当它已经应用了离开范围时。
例如:假设一名员工已于2015年1月1日至2015年1月5日期间申请休假,
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查询找到它
答案 0 :(得分:5)
你可以尝试如下
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 !";
}
答案 1 :(得分:3)
试试这个:
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");
}
答案 2 :(得分:1)
另一种更好的方法是为DateTime类创建一个扩展方法:
public static bool Between(this DateTime input, DateTime date1, DateTime date2)
{
return (input > date1 && input < date2);
}
然后你可以将它与linq predicate where子句一起使用。
if(leaves.Where(l =&gt; l.empId == empId&amp;&amp; dateApplied.Between(l.from,l.to))。Any()) {...错误...}
PS:这只是你方向的伪代码。
答案 3 :(得分:0)
IF EXISTS (
SELECT * FROM table WHERE user = @user AND (
@newStartDate BETWEEN appliedStartDate AND appliedEndDate
)
PRINT 'Can not apply'
ELSE PRINT 'Can apply'
答案 4 :(得分:0)
这篇文章与范围内两列之间的查询有关,这可能对某些开发人员有所帮助。
第一步:进入列表
var Price = GetLoad()。ToList();
第二步:您的搜索项
字符串代码=“ PLUS”;
var Total_Squares = 101://需要在整数范围内检查值
DateTime Checkdate = Convert.ToDateTime(“ 2012-10-03”); //需要在日期内检查值
Query1检查整数范围以及字符串值
varfilteredCodeWithSquare = Price.Where(C => C.Code.StartsWith(code))
.FirstOrDefault(r => r.FromSquare <= Total_Squares && r.ToSquare> = Total_Squares); 一种 Query2检查日期范围
var daterange = Price.FirstOrDefault(d => d.FromIntall
<= Checkdate && d.ToInstall> = Checkdate);