在数据范围内返回数据库结果 [英] Return DB results within Date Range

查看:149
本文介绍了在数据范围内返回数据库结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我看来,我有一个输入和选择标签,供用户输入开始和结束日期。
提交时,控制器将搜索模型/数据库并返回上述范围内的条目。



在我的数据库中,开始和结束日期写为nvarchars,在我的控制器中,它们被作为字符串



代码和图片供参考:

  public ActionResult timePeriod(string time)
{
//开始:月,日,年结束:月,日,年 - >数值
string [] times = time.Split(',');
string start = times [0] ++ times [1] ++ times [2];
string end = times [3] ++ times [4] ++ times [5];

//测试开始日期的示例代码
viewModel.Tasks = db.Tasks.Where(s => s.StartTime.Contains(start))ToList();
}

数据库值的一个片段:





是否有任何LINQ表达式来执行此操作?

解决方案

由于日期是字符串,除了使用你已经建议:

  viewModel.Tasks = db.Tasks.Where(s => s.StartTime.Equals(start ))ToList(); 

我将使用等于更快你使用包含基本上就像做一个T-SQL LIKE 这慢得多。

  SELECT * 
FROM Table
WHERE StartDate LIKE'blah'

使用等于将导致以下等价物:

  SELECT * 
FROM Table
WHERE StartDate ='blah'

哪种效率更高。 / p>

In my view, I have an input and select tags for the user to enter a start and end date. When submitted, The controller will search the Model/Database and return entries within the above range.

In my DB, the start and end dates are written as "nvarchars" and in my controller they are taken as strings

Code and Images for reference:

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];

    //Sample code to test the start date
    viewModel.Tasks = db.Tasks.Where(s => s.StartTime.Contains(start)).ToList();
}

a snippet of the Database values:

Are there any LINQ expression to do this?

解决方案

As the dates are strings, you've nothing better other than using what you have suggested already:

viewModel.Tasks = db.Tasks.Where(s => s.StartTime.Equals(start)).ToList();

I would use Equals as that will be quicker for you. Using Contains is basically like doing a T-SQL LIKE which is much slower.

SELECT *
FROM Table
WHERE StartDate LIKE 'blah'

Using Equals will result in the following equivalent:

SELECT *
FROM Table
WHERE StartDate = 'blah'

Which is much more efficient.

这篇关于在数据范围内返回数据库结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆