实体框架/ LINQ - 日期从/日期到比较

时间:2015-12-09 17:46:51

标签: entity-framework linq date entity

我有一个非常简单的情况,但我无法在网上找到答案。

我希望实现一个简单搜索表单,它允许用户查询数据库记录,其中包含用户选择的From Date和To Date 之间的时间戳。用户也可以按文本字段的子字符串过滤结果,称为样本编号。

如果我只进行子字符串搜索并删除比较where子句中的日期的功能,则查询有效。 只要我在where子句中比较日期,查询就不会返回任何结果。

以下是不同测试的结果:

此查询会搜索范围的日期,并且根本不会产生任何结果(当应该有一些权利时),所以这不起作用:

public List<devicereading> getDeviceReadings(String entityConnStr, DateTime fromDate, DateTime toDate, String sampleNo)
{
    labinstrumentconnection lc = new labinstrumentconnection(entityConnStr);
    List<devicereading> ll = lc.devicereadings.Where(d => d.datetime >= fromDate && d.datetime <= toDate && d.samplenumber.Contains(sampleNo)).ToList();
    return ll;
}

这只搜索单个日期比较即。对于仅在给定日期之后的日期但它也不会产生任何结果,所以这不起作用:

public List<devicereading> getDeviceReadings(String entityConnStr, DateTime fromDate, DateTime toDate, String sampleNo)
{
    labinstrumentconnection lc = new labinstrumentconnection(entityConnStr);
    List<devicereading> ll = lc.devicereadings.Where(d => d.datetime >= fromDate).ToList(); 
    return ll;
}

这个只进行子字符串搜索并执行无日期比较。这个有效!

public List<devicereading> getDeviceReadings(String entityConnStr, DateTime fromDate, DateTime toDate, String sampleNo)
{
    labinstrumentconnection lc = new labinstrumentconnection(entityConnStr);
    List<devicereading> ll = lc.devicereadings.Where(d => d.samplenumber.Contains(sampleNo)).ToList();
    return ll;
}

我再也看不出有什么问题了。希望有人可以看到问题所在。

非常感谢。

1 个答案:

答案 0 :(得分:0)

您应该使用DbFunction.TruncateTime命名空间中的System.Data.Entity来比较日期而无需担心时间。

public List<devicereading> getDeviceReadings(String entityConnStr, DateTime fromDate, DateTime toDate, String sampleNo)
{
    labinstrumentconnection lc = new labinstrumentconnection(entityConnStr);
    var fromDateWithoutTime = fromDate.Date
    List<devicereading> ll = lc.devicereadings.Where(d => DbFunction.TruncateTime(d.datetime) >= fromDateWithoutTime).ToList(); 
    return ll;
}

public List<devicereading> getDeviceReadings(String entityConnStr, DateTime fromDate, DateTime toDate, String sampleNo)
{
    labinstrumentconnection lc = new labinstrumentconnection(entityConnStr);
    var toDateWithoutTime = toDate.Date
    var fromDateWithoutTime = fromDate.Date
    List<devicereading> ll = lc.devicereadings.Where(d => DbFunction.TruncateTime(d.datetime) >= fromDateWithoutTime && DbFunction.TruncateTime(d.datetime) <= toDateWithoutTime && d.samplenumber.Contains(sampleNo)).ToList();
    return ll;
}