2014-12-03 94 views
0

昨天我问了一个问题,我必须在给定的日期范围内返回数据库记录。 在昨天的问题中,我曾经说过,在数据库表中,日期是'nvarchar'类型,联系数据库管理员后。现在C#:在日期范围内获取数据库记录

的类型已经更改输入“日期时间”

因此,我要寻找一个LINQ表达式给定的日期范围内返回数据库记录。 前一题链接:Return DB results within Date Range

代码:

public ActionResult timePeriod(string time) 
{ 
    //Start: month, day, year End: month, day, year --> Numeric values 
    string[] times = time.Split(',');        
    string start = times[0] + " " + times[1] + " " + times[2]; 
    string end = times[3] + " " + times[4] + " " + times[5]; 

    var sDate = DateTime.Parse(start); 
    var eDate = DateTime.Parse(end); 

    //viewModel.Tasks = db.Tasks. //Linq expression to return values withing range. 
    viewModel.EngineerSkills = db.EngineerSkills.ToList(); 
    viewModel.Categories = db.TaskCategories.ToList(); 

    gatherInfo(viewModel); 
    gatherXML(); 
    timeRestrictions(viewModel); 
    gatherMapPositions(viewModel); 

    return View("Index", viewModel); 
} 

回答

1
//previous code 
..... 
var viewModelDates = viewModel.Where(p=>p.StartTime >=sDate && p.EndTime<=eDate); 
return View("Index", viewModelDates.ToList()); 

你应该检查哪里StartTime>=sDate and p.EndTime<=endTime。这应该会返回正确的值。我希望你有效的sDateeDate

+1

谢谢! 从我做过的一些研究中没有想到它会变得这么简单! – 2014-12-03 15:46:07

+1

@StephenSugumar没有问题与您的项目好运;) – mybirthname 2014-12-03 15:47:51

0

请试试这个:

viewModel.Tasks = db.Tasks.Where(s => DbFunctions.TruncateTime(s.StartTime) == DbFunctions.TruncateTime(sDate)).ToList(); 
+1

这只能获得开始日期的任务。 不是解决方案 – 2014-12-03 15:42:57

1

我现在不如果即时通讯understund您的问题或没有,试试这个代码

var query = (from a in announcements 
     where (a.Begins <= RightNow) && (a.Expires >= RightNow) 
     select a).ToList(); 
+0

这是行不通的。 – 2014-12-03 15:43:55

+0

什么是DB – 2014-12-03 15:49:24

+0

中的日期磁带,其中t.date> = new DateTime(2007,9,9)&& t.date 2014-12-03 15:51:57