【问题标题】:C# Linq to SQL Query between 2 Dates nos getting resultsC# Linq to SQL Query 2 Dates nos getting results
【发布时间】:2018-06-26 13:48:04
【问题描述】:

我正在使用文本框、组合框和 DateTimePicker 构建复杂的搜索查询。

对于文本框和组合框,查询工作正常,但是当为两个日期之间的查询添加 datetimepicker 时,我什么也得不到...

在 LINQ 中使用 EF6...

所以,我的类来存储数据:

public class Projetos
    {
        public int ID { get; set; }
        public string Conc { get; set; } //Combobox
        public string Ent { get; set; } //Combobox
        public string Def { get; set; } //Textbox
        public DateTime DataR { get; set; }
    }

第一次查询并返回结果:

public IEnumerable<Proj> LoadProj()
    {
        var ctx = new JEntities();
        var query = (from p in ctx.tblProjs.AsQueryable()
                     join c in ctx.tblConcs on p.ConcID equals c.ConcID
                     join e in ctx.tblEnts on p.EntID equals e.EntID
                     select new Proj
                     {
                         ID = p.ProjID,
                         Conc = c.NameConc,
                         Ent = e.NameEnt,
                         Def = p.DefP,
                         DataR = p.DataR
                     });
        // The combination of these 3 controls works fine!           
        if (TxtDefP.TextLength > 0)
        {
            query = query.Where(s => s.DefP.Contains(TxtDefP.Text));
        }
        if(CmbCon.SelectedValue != null)
        {
            string SelectedValue = CmbConc.GetItemText(CmbConc.SelectedItem);
            query = query.Where(s => s.Conc == SelectedValue);
        }
        if(CmbEnt.SelectedValue != null)
        {
            string SelectedValue = CmbEnt.GetItemText(CmbEnt.SelectedItem);
            query = query.Where(s => s.Ent == SelectedValue);
        }

        //When filtering between these 2 dates, I get no results

        if (DataRFrom.Checked && DataRTo.Checked)
        {
            DateTime begin = DataRFrom.Value.Date;
            DateTime end = DataRTo.Value.Date;
            query = query.Where(s => s.DataR > begin && s.DataR < end);
        }
        return query.ToList();
    }

在 SQL 中,我有这样的日期......也许 SQL 中的日期格式搞砸了这一切???

我的问题是,为什么我无法在 2018-06-01 和 2018-06-06 之间获得任何结果,因为此日期范围的记录在数据库中?

谢谢。

【问题讨论】:

  • DataRFromDataRTo 的值是多少?您使用的是什么 RDBMS(Oracle、MSSQL、MySQL...)?
  • DataRFrom 是一个 DateTimePicker,字符串格式为 yyyy-MM-dd。我正在使用 MSSQL。
  • 跟踪数据库并查看SQL
  • 选择 DataRFrom = 2018-06-20 和 DataRTo=2018-06-30 的结果是什么?
  • 结果是一个空表,因为我的查询结果将填充一个datagridview。如果查询没有结果,datagridview 将为空!

标签: c#


【解决方案1】:

缺少日期属性:

query = query.Where(s => s.DataR.Date > begin && s.DataR.Date

【讨论】:

  • 使用 DataR.Date 时出现错误...“LINQ to Entities 不支持指定的类型成员 'Date'”。
  • DateTimePicker 上没有 Date 属性
  • 废话,我的错,你确实是对的,没有财产。
猜你喜欢
  • 2021-01-02
  • 1970-01-01
  • 2021-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多