C# EF按日期查詢時出錯

eftable表映射以後的代碼以下:html

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

按日期時間查詢代碼以下:express

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就產生了錯誤,沒法轉換爲存儲表達式。this

解決辦法是:將用戶輸入的起始日期的轉換提早一步,使用真正的C#代碼完成,而後將轉換後的變量代入到LINQ表達式內。https://blog.csdn.net/qiujuer/article/details/41868331 中有一個推薦方法,我修改以後的代碼以下:.net

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());
            }
相關文章
相關標籤/搜索