2014-12-03 95 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