C# EF按日期查询时出错

eftable表映射之后的代码如下:

public partial class eftable
    {
        public int id { get; set; }
        public string name { get; set; }
        public Nullable<int> age { get; set; }
        public Nullable<System.DateTime> efdate { get; set; }
    }

按日期时间查询代码如下:

private void button1_Click(object sender, EventArgs e)
        {
            testEntities db = new testEntities();
            DateTime dt2 = DateTime.Parse("2018/5/23 8:45:28");
            var ef = db.eftable.Where<eftable>(feftable => compareDateTimesecond(feftable.efdate ,dt2)>2); 
            var counts = ef.Count();
            foreach(var item in ef)
            {
                Console.WriteLine(item.id + ":" + item.name + ":" + item.age);
            }
        }
        private int compareDateTimesecond(Nullable<DateTime> dtsrc, DateTime dtdes)
        {
            if (!dtsrc.HasValue)
                return -1;
            TimeSpan tssrc = new TimeSpan(dtsrc.Value.Ticks);
            TimeSpan tsdes = new TimeSpan(dtdes.Ticks);
            TimeSpan ts = tssrc.Subtract(tsdes).Duration();
            return ts.Seconds;
        }

我将断点打在compareDateTimesecond函数中的第一句上,但调试时不进入断点处,直接运行到var counts =ef.Count()处,并且总是出现:

“System.NotSupportedException”类型的未经处理的异常在 EntityFramework.dll 中发生 

其他信息: LINQ to Entities does not recognize the method 'Int32 compareDateTimesecond(System.Nullable`1[System.DateTime], System.DateTime)' method, and this method cannot be translated into a store expression.

根据 https://www.cnblogs.com/wusir/p/3477435.html 所说,本表达式只是LINQ to Entities,而不是真正的C#语言,虽然上述代码在编译是没有错误,但运行时,转换为SQL就产生了错误,无法转换为存储表达式。

解决办法是:将用户输入的起始日期的转换提前一步,使用真正的C#代码完成,然后将转换后的变量代入到LINQ表达式内。https://blog.csdn.net/qiujuer/article/details/41868331 中有一个推荐方法,我修改之后的代码如下:

var ef = db.eftable.ToList().Where(f => f.efdate > dt2 && f.efdate < dt3).OrderByDescending(i => i.id).Skip(2).Take(3).Select(u => new { name = u.name, age = u.age, id = u.id, efdate = u.efdate });
            foreach(var item in ef)
            {
                Console.WriteLine(":" + item.name + ":" + item.age + ":" + item.efdate.ToString());
            }

转载于:https://my.oschina.net/u/2963604/blog/1817082

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值