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 中有一个推荐方法,我修改之后的代码如下:

猜你喜欢

转载自my.oschina.net/u/2963604/blog/1817082