如何使用实体框架在C#,ASP.NET MVC 3中的两个日期之间获取记录?

时间:2018-07-12 05:24:18

标签: c# asp.net-mvc entity-framework

我无法在两个日期之间获取记录。

我尝试使用普通查询,但未得到任何结果:

 log.Info("Parameters Received...");
 log.Info("name:"+param1); // => "SELECT"
 log.Info("city:"+param2); // => "SELECT"
 log.Info("userId :"+userId); // =>""
 log.Info("creationDateFrom :"+creationDateFrom); // => 10/07/2018
 log.Info("creationDateTo :"+creationDateTo); // => 12/07/2018     

var report = reportDBObj.tbl_reports.AsQueryable();

if (param1 != null && !param1.Equals("SELECT")) 
     report = report.Where(x => x.name == param1);

if (param2 != null && !param2.Equals("SELECT")) 
     report = report.Where(x => x.city == param2);

if (userId != null && userId != "") 
     report = report.Where(x => x.user_id == userId);

Boolean dateCheck = false;
DateTime createDateFrom = DateTime.MinValue, createDateTo = DateTime.MinValue;

if (!string.IsNullOrEmpty(creationDateFrom))
{
    // createDateFrom = Convert.ToDateTime(creationDateFrom);
    createDateFrom = DateTime.Parse(creationDateFrom);
    dateCheck = true;
}

if (!string.IsNullOrEmpty(creationDateTo))
{
    // createDateTo = Convert.ToDateTime(creationDateTo);
    createDateTo = DateTime.Parse(creationDateTo);

    if (!dateCheck)
        dateCheck = true;
}

if (dateCheck)
{
    if (createDateFrom == DateTime.MinValue)
        createDateFrom = DateTime.Now;
    else if (createDateTo == DateTime.MinValue)
        createDateTo = DateTime.Now;
}

if (dateCheck)
{
    Debug.WriteLine("createDateFrom :" + createDateFrom);
    Debug.WriteLine("createDateTo :" + createDateTo);

    report = report.Where(x => x.creation_date >= createDateFrom && x.creation_date <= createDateTo); // this line returns no records
}

repListTbl = report.OrderByDescending(x => x.creation_date).ToList();

我的代码怎么了?

谢谢

1 个答案:

答案 0 :(得分:4)

两种方法。

首先带有两个WHERE子句

SUCCESS

第二个带有一个WHERE子句和MIN MAX

INFO

如果未取得任何结果,请检查数据库中各列的日期格式,并且记录确实存在。